我无法弄清楚如何从我的后期路由和组件中的父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> ); } });
将pushToPostList = {this.pushToPostList}移动到App Class.
原文链接:https://www.f2er.com/react/301075.htmlvar 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> ); } });