[英]Binding event handler prop with react-redux
從容器到演示文稿小部件聲明事件處理程序的正確方法是什么,以便我可以訪問事件處理程序功能中的其他道具?
class ApplicationWidget extends Component {
componentDidMount() {
this.props.handle_onload.call(this);
}
render() {
return (
<div onClick={this.props.handle_click}>
<Header />
<Content />
</div>
);
}
}
export default connect(
state => {
return {foo: state.foo};
},
dispatch => {
return {
handle_click() {
console.log(this)
},
handle_onload() {
jQuery.get({
accepts: 'application/json',
success: (data) => dispatch(the_action_creator(data)),
url: `/initialize`
});
}
};
}
)(ApplicationWidget);
當前,每當單擊事件發生時, this.props.handle_click
事件處理程序都會記錄undefined
的日志。 如果我想訪問this.props.foo
,正確的方法是什么? 我當前的實現是
<div onClick={this.props.handle_click.bind(this)}>
在render()
方法中,它可以按預期工作,但是根據lint,這似乎不是一個好習慣。 在更新容器(由connect
函數生成)后(由於某種原因綁定重置為undefined
),以下代碼似乎不起作用
constructor(props) {
super(props);
this.props.handle_click = this.props.handle_click.bind(this)
}
那么正確的方法是什么呢? 還是我整個事情做錯了?
prop handle_click
只是一個通過引用傳遞給組件的函數,因此它不“了解”有關組件范圍( this )的任何信息。 您可以使用所有功能都可用的bind方法來更改它,如下所示:
class ApplicationWidget extends Component {
componentDidMount() {
this.props.handle_onload.call(this);
}
render() {
return (
<div onClick={this.props.handle_click.bind(this)}>
<Header />
<Content />
</div>
);
}
}
為了優化這一點並防止您的lint抱怨,可以將其綁定到構造函數中,如下所示:
class ApplicationWidget extends Component {
constructor(props) {
super(props);
this.handle_click = props.handle_click.bind(this);
}
componentDidMount() {
this.props.handle_onload.call(this);
}
render() {
return (
<div onClick={this.handle_click}>
<Header />
<Content />
</div>
);
}
}
因此,您幾乎完全正確,但我不會在構造函數中修改props,只需在類中添加另一個方法即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.