3
我試圖專注於一個div,當我點擊一個按鈕像here。我將問題簡化爲下面的代碼,雖然在div對象上調用焦點,但onFocus從不會被調用。另外autoFocus
不能解決我的問題,因爲我希望能夠在組件安裝後多次更改焦點。React無法專注於div
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>
);
}
}
這是包含此代碼的fiddle。
謝謝!事實上,tabindex =「0」允許除鏈接和表單元素之外的元素接收鍵盤焦點,就像我剛學會的那樣。 –