我无法弄清楚如何从我的post
路由和组件中的父ReactJS组件访问方法。使用react-router
。
这是
<RouteHandler {...this.state} />
方法/函数pushToPostList()
将一个post对象添加到一个数组中,保存在this.state.myList
中。
尝试让我的<Post />
组件正常工作,以便调用this.props.pushToPostList(newPost)
更新<App />
中的this.state.myList
路由器是:
var routes = (
<Route handler={App} >
<DefaultRoute handler={SignUp} />
<Route name="feed" path="feed" handler={LatestFeed} />
<Route name="post" path="post" handler={Post} pushToPostList={this.pushToPostList} />
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler />, document.body );
});
更多代码:
var App = React.createClass({
getInitialState: function() {
return {
myList: []
};
},
pushToPostList: function (object) {
if (object) {
var myTempPosts = this.state.myPostList;
myTempPosts.push(object);
this.setState( {myPostList: myTempPosts} );
}
},
render: function() {
return (
<div>
<RouteHandler {...this.state} />
</div>
);
}
});
var Post = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var myPostTxt = this.refs.myPostTxt.getDOMNode().value.trim();
this.props.pushToPostList( myPostTxt ); // Send object to parent ReactJS component.
},
render: function() {
return (
<div>
Post.
<textarea
ref="myPostTxt" />
<p />
<button onClick={this.handleSubmit} type="submit">Post</button>
</div>
);
}
});
答案 0 :(得分:4)
将pushToPostList = {this.pushToPostList}移至App Class。
var App = React.createClass({
getInitialState: function() {
return {
myList: []
};
},
pushToPostList: function (object) {
if (object) {
var myTempPosts = this.state.myPostList;
myTempPosts.push(object);
this.setState( {myPostList: myTempPosts} );
}
},
render: function() {
return (
<div>
<RouteHandler {...this.state} pushToPostList={this.pushToPostList} />
</div>
);
}
});