[英]How to get a React component in a function by onClick
我需要獲得一個我喜歡的組件並查看其目標屬性。 我嘗試獲取它,但evt參數未定義
getcomponent(evt){
console.log(evt.target)
//...
}
//...
render() {
return (<button id="btn" onClick={() =>this.getcomponent()}></button>);
}
將event
作為參數添加到onClick
:
render() {
return (<button id="btn" onClick={(event) =>this.getcomponent(event)}></button>);
}
您沒有將事件傳遞給函數調用。 通過這樣的事件: onClick={(evt) => this.getcomponent(evt)}
。
使代碼簡短:
onClick = event => {
console.log(event.target)
}
render() {
return <button id="btn" onClick={this.onClick}></button>
}
您需要傳遞事件才能恢復原狀。 這是代碼。
class TestJS extends React.Component { constructor(props) { super(props); this.getcomponent = this.getcomponent.bind(this); } getcomponent(event){ console.log(event.target); } render() { return( <div id="root"> <button id="btn" onClick={(event) =>this.getcomponent(event)}></button>; </div> )}; } export default TestJS;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.