[英]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.