8

我不知道如何从我的post路由和组件中的父 ReactJS 组件访问方法。使用react-router.

这是在 <RouteHandler {...this.state} />

中的方法/函数pushToPostList()将一个 post 对象添加到一个数组中,保存在this.state.myList.

试图让我的<Post />组件工作,所以它调用this.props.pushToPostList(newPost)更新 this.state.myList<App />

路由器是:

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>
        );
    }
});
4

1 回答 1

4

将 pushToPostList={this.pushToPostList} 移至 App 类。

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>
    );
}
});
于 2015-04-05T15:55:56.063 回答