我在学习 React 时遇到了一个小问题 - 我想分散注意力(又名 blur()
)按钮 DOM 元素,但出于某种原因,这不太有效。
据我所知,我认为问题在于 reactstrap Button
组件的使用:
<Button className={buttonClass} onClick={this.handleCopyToClipboardClick} ref={this.buttonBlurRef}>
<div className="d-flex justify-content-between">
<span></span>
<span>{ this.state.hasCopiedToClipboard ? 'Copied to clipboard!' : this.state.buttonText }</span>
<span><FontAwesomeIcon icon="copy" /></span>
</div>
</Button>
我要在组件上绑定(bind)一个 ref?我认为这就是它不起作用的原因。
onClick
函数正在运行,我已将其包含在下面。我从我尝试过的东西中加入了一些注释掉的代码 - 所有这些都破坏了 handleCopyToClipboardClick
函数。
handleCopyToClipboardClick() {
this.setState(state => ({
hasCopiedToClipboard: !state.hasCopiedToClipboard
}));
// this.buttonBlurRef.current.blur(); <= This isn't working
// this.buttonBlurRef.blur(); <= This isn't working either
// this.refs.buttonBlurRef.current.blur(); <= Or this
// this.refs.buttonBlurRef.blur(); <= Nor this... :'(
setTimeout(
function() {
this.setState(state => ({
hasCopiedToClipboard: !state.hasCopiedToClipboard
}));
}.bind(this),
1500
);
}
这也是我的组件构造函数:
constructor(props) {
super(props);
this.buttonBlurRef = React.createRef();
this.state = {
hasCopiedToClipboard: false,
};
this.handleCopyToClipboardClick = this.handleCopyToClipboardClick.bind(this);
}
任何关于我如何可能不关注我的 Bootstrap Button
的建议都会很棒! :)
最佳答案
您的文档中有一个 activeElement
属性,因此您可能只需调用 document.activeElement.blur()
并且它应该可以工作。您也可以尝试其他方式,而不是在您的元素上调用模糊 - 将焦点放在其他元素上,例如整个文档:window.focus()
或 document.body。焦点()
。希望这有帮助
关于javascript - Reactjs:使用 .blur() 取消聚焦按钮元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54056596/