reactjs – 如何使用react-router将this.state和this.props传递给路由

前端之家收集整理的这篇文章主要介绍了reactjs – 如何使用react-router将this.state和this.props传递给路由前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法弄清楚如何从我的后期路由和组件中的父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.
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>
    );
}
});

猜你在找的React相关文章