我试图清理我的组件,以便我的容器处理逻辑,我的组件只是表示。我使用Redux将我的商店连接到容器/组件。
我正在尝试这个简单的代码,而且我不确定它为什么不起作用以及我缺少的东西。
以前我曾经,并且它有效:
var Main = React.createClass({
render: function(){
var style = this.props.hover;
var actions = this.props.actions;
return (
<div>
<Bullet style={style} actions = {actions}/>
</div>
);
}
});
function mapStateToProps(state) {
return {
hover: state.hover
}
}
function mapDispatchToProps(dispatch) {
return {
actions: Redux.bindActionCreators(actions, dispatch)
}
}
var MainConnected = connect(mapStateToProps, mapDispatchToProps) (Main);
module.exports = MainConnected;
这是我的Bullet
组件:
var Bullet = React.createClass({
over: function(){
this.props.actions.ON();
},
out: function(){
this.props.actions.OFF();
},
render: function(){
var style = this.props.style;
return(
<div id="bullet" style = {style} onMouseOver = {this.over} onMouseOut = {this.out}></div>
);
}
});
现在,我尝试了这个:
var Main = React.createClass({
over: function(){
console.log('hey');
},
out: function(){
this.props.dispatch(actions.OFF());
},
render: function(){
var style = this.props.hover;
return (
<div>
<Bullet id="Git" style={style} onMouseOver = {this.over} onMouseOut = {this.out}/>
</div>
);
}
});
//and Bullet component
var Bullet = React.createClass({
render: function(){
var style = this.props.style;
return(
<div id="bullet" style = {style} ></div>
);
}
});
我从over
删除了out
和Button
逻辑,但是当从主容器调用时它们不起作用。我想我也误解了如何使用this
,因为console.log()
没有被调用。
感谢您指导我如何分离这个逻辑,并帮助理解如何在React中使用this
。谢谢!
答案 0 :(得分:0)
我必须将我的功能从Parent传递给Child。所以代码看起来像这样:
var Main = React.createClass({
over: function(){
this.props.dispatch(actions.ON());
},
out: function(){
this.props.dispatch(actions.OFF());
},
render: function(){
var style = this.props.hover;
return (
<div>
<Bullet id="Git" style={style} over = {this.over} out = {this.out}/>
</div>
);
}
});
var Bullet = React.createClass({
render: function(){
var style = this.props.style;
var over = this.props.over;
var out = this.props.out;
return(
<div id="bullet" style = {style} onMouseOver = {over} onMouseOut = {out}></div>
);
}
});