当我点击像
here这样的按钮时,我试着把注意力集中在一个div上.我将我的问题减少到下面的代码,虽然在div对象上调用焦点,但是永远不会调用onFocus.此外,autoFocus无法解决我的问题,因为我希望能够在组件安装后多次更改焦点.
class App extends React.Component { constructor() { super(); this.my_refs = {}; this.focusByID.bind(this); } focusByID(id){ let myRef = this.my_refs[id]; if(myRef){ console.log('focusing on ',id,myRef); myRef.focus(); } } render() { return ( <div> <div id="bigRedDiv" style={{height : 200,width : 200,backgroundColor : 'red'}} ref={(input) => this.my_refs['bigRedDiv'] = input } onFocus={() => console.log('FOCUS IS ON BIG RED DIV')} onClick={() => this.focusByID('bigRedDiv')} > </div> </div> ); } }
只是:
... <div tabIndex="0" //use this attribute id="bigRedDiv" style={{height : 200,backgroundColor : 'red'}} ref={(input)=> this.my_refs['bigRedDiv'] = input } onFocus={() => console.log('FOCUS IS ON BIG RED DIV')} onClick={() => this.focusByID('bigRedDiv')} > </div> ...