我有一个组件在focus()
和componentDidMount
期间在引用组件上触发componentDidUpdate
。另外,当我们点击外面时,我的功能不会触发onClose。当我点击onBlur
外部时,我再次触发focus
以继续关注元素。什么是最好的方法?为什么在某些情况下我看到更好地使用setTimeout onblur?
export class Test extends Component {
componentDidMount = () => this.focusContainer()
componentDidUpdate = () => this.focusContainer()
container = React.createRef()
focusContainer = () => this.container.current.focus()
render = () => {
return (
<div
style={{outline: 'none'}}
onKeyPress={this.captureInput}
onBlur={this.focusContainer} // or onBlur={() => setTimeout(() => this.focusContainer(), 0) } - why ?
ref={this.container}
// tabIndex is needed for focus/blur to work on non input type elements.
tabIndex={0}
>
<img src={scanTag} style={{maxWidth: '100%'}} alt='scan tag via scanner' />
..........
</div>
)
}
}