分离表示和逻辑组件react / redux [英] Separating presentational and logic components react/redux
问题描述
我正在尝试清理组件,以便我的容器处理逻辑,并且组件仅是表示性的。我正在使用Redux将商店连接到容器/组件。
I'm trying to clean up my components so that my container handles logic and my components are presentational only. I'm using Redux to connect my store to container/components.
我正在尝试这个简单的代码,但不确定为什么它不起作用以及什么原因我不见了。
I'm trying this simple code, and I'm not sure why it is not working and what I'm missing.
以前我有,而且有效:
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>
);
}
});
现在,我尝试了此操作:
Now, I tried this:
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
和<$ c从 Button
中的$ c> out 逻辑,但是当从Main容器调用它们时,它们不起作用。我想我也误会了如何使用 this
,因为没有调用 console.log()
。
I removed the over
and out
logic from the Button
but they're not working when called from the Main container. I think I'm misunderstanding how to use this
too because the console.log()
is not being called.
感谢您为我指出了如何分隔此逻辑的正确方向,也许还帮助您了解了如何使用 在React中谢谢!
Thanks for pointing me in the right direction as to how to separate this logic and maybe helping understand how this
is used in React. Thanks!
推荐答案
哦,知道了。
这有助于: ReactJS:将onClick处理程序放在子组件上时不会触发
我必须将函数从父级传递给子级。因此代码如下所示:
I had to pass my functions from Parent to Child. So the code looks like this:
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>
);
}
});
这篇关于分离表示和逻辑组件react / redux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!