【发布时间】:2016-10-05 07:02:25
【问题描述】:
我是 react 和 redux 的新手。我正在尝试将我的组件分成容器和演示组件。 到目前为止,我通过将动作和状态作为道具从容器传递到组件来设法将它们分开。
它们的外观如下:
容器:
class HelpForm extends React.Component{
constructor(props, context) {
super(props, context);
this.state = {
help: { message: "" }
};
}
render(){
return (
<HelpFormUI actions={this.props.actions} helps={this.props.helps} />
);
}
}
HelpForm.propTypes = {
actions: PropTypes.object.isRequired,
helps: PropTypes.array.isRequired
};
function mapStateToProps(state, ownProps){
return {
helps: state.helps
};
}
function mapDispatchToProps(dispatch){
return {
actions: bindActionCreators(helpActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(HelpForm);
演示文稿:
onClickPost(event){
this.props.actions.createHelp(this.state.help);
}
render(){
return (
<div>
<h2>What can you help today?</h2>
<input
type="text"
onChange={this.onMessageChange}
value={this.state.help.message} />
<input
type="submit"
value="Post"
className="btn btn-primary"
onClick={this.onClickPost} />
</div>
);
我的问题是:可以将动作和状态作为道具传递给孩子吗?如果不是,正确的方法是什么?我也想知道,如何在不将其作为道具传递给孩子的情况下访问父母的状态?
谢谢!
【问题讨论】: