首页 > 解决方案 > React 保持专注于Blur

问题描述

我有一个在和期间触发focus()ref 组件的组件。此外,当我们在外部单击时,我还有不会触发 onClose 的功能。当我点击外部时,我再次触发以保持对元素的关注。最好的方法是什么?为什么在某些情况下我看到更好地使用 setTimeout onblur?componentDidMountcomponentDidUpdateonBlurfocus

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>
       )
    }
}

标签: javascriptreactjsecmascript-6onbluronfocus

解决方案


推荐阅读