【发布时间】:2018-03-27 08:28:43
【问题描述】:
将事件处理程序从容器声明到表示小部件以便我可以访问事件处理程序函数中的其他道具的正确方法是什么?
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() 方法中,它按预期工作,但是根据linter,这看起来不是一个好习惯。更新容器(由connect 函数生成)后,以下代码似乎不起作用(由于某种原因,绑定重置为undefined)
constructor(props) {
super(props);
this.props.handle_click = this.props.handle_click.bind(this)
}
那么正确的方法是什么?还是我做错了整件事?
【问题讨论】:
-
我知道因此我正在寻找正确的方法(:
标签: javascript reactjs ecmascript-6 redux react-redux