更改 Font Awesome 按钮样式 onClick

我有一个样式为 Font Awesome 的按钮。


              <button

                onClick={this.changeLockButtonStyle}

                id="LockButton"

                >

                <FaLockOpen />

              </button>

我正在尝试找到一种方法将样式更改为<FaLockClosed />从在线阅读中我看到的唯一示例是关于 JQuery 和 class=”fas fa-lockclosed” 切换类。但我使用的是按钮,而不是普通图标。我已经尝试过document.getElementById('LockButton').innerHTML= '<FaLockClosed />'但没有用。如果可能,我想避免使用 JQuery。


LEATH
浏览 151回答 3
3回答

PIPIONE

干得好:const [isLocked, setIsLocked] = useState(false);return (&nbsp; &nbsp; <button&nbsp; &nbsp; &nbsp; &nbsp; type="button"&nbsp; &nbsp; &nbsp; &nbsp; onClick={() => { setIsLocked(true); }}&nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; {isLocked ? <FaLockClose /> : <FaLockOpen />}&nbsp; &nbsp; </button>);更新:这就是你在类组件中的做法。constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; &nbsp; isLocked: false&nbsp; &nbsp; };&nbsp; &nbsp; this.lockIcon = this.lockIcon.bind(this);}lockIcon() {&nbsp; &nbsp; this.setState({ isLocked: true });}render() {&nbsp; &nbsp; const { isLocked } = this.state;&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="button"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={this.lockIcon}&nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {isLocked ? <FaLockClose /> : <FaLockOpen />}&nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; );}

呼唤远方

我的最佳实践解决方案是使用 css 类。但如果你做不到,你可以使用由 javascript 变量控制的 2 个图标的显示状态。

达令说

如果您使用反应或角度,我只会根据按下按钮期间设置的变量切换组件。有关如何在 React 中进行切换的参考 https://stackoverflow.com/a/46425155/14167216这是一个 jQuery 示例。您可以在按钮上设置类,然后检查按钮是否有类。如果它有锁定类,则更改为解锁类,反之亦然。检查下面的示例代码。function changeLockButtonStyle() {&nbsp; var icon = $('#LockButton')&nbsp; var hasLock = icon.hasClass('fa-lock');&nbsp; if(hasLock) {&nbsp; &nbsp; &nbsp;icon.removeClass('fa-lock').addClass('fa-unlock');&nbsp; } else {&nbsp; &nbsp; &nbsp;icon.removeClass('fa-unlock').addClass('fa-lock');&nbsp; }}<head>&nbsp; &nbsp; <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>&nbsp; &nbsp; <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"></head><body>&nbsp; &nbsp; <button&nbsp; &nbsp; &nbsp; onClick='changeLockButtonStyle()'&nbsp; &nbsp; &nbsp; id="LockButton"&nbsp; &nbsp; &nbsp; class="fa fa-lock"&nbsp; &nbsp; >&nbsp; &nbsp; </button></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript