ReactJS:在子组件内的父级上的setState

从子组件对父进行setState的build议模式是什么?

var Todos = React.createClass({ getInitialState: function() { return { todos: [ "I am done", "I am not done" ] } }, render: function() { var todos = this.state.todos.map(function(todo) { return <div>{todo}</div>; }); return <div> <h3>Todo(s)</h3> {todos} <TodoForm /> </div>; } }); var TodoForm = React.createClass({ getInitialState: function() { return { todoInput: "" } }, handleOnChange: function(e) { e.preventDefault(); this.setState({todoInput: e.target.value}); }, handleClick: function(e) { e.preventDefault(); //add the new todo item }, render: function() { return <div> <br /> <input type="text" value={this.state.todoInput} onChange={this.handleOnChange} /> <button onClick={this.handleClick}>Add Todo</button> </div>; } }); React.render(<Todos />, document.body) 

我有一系列在父母状态下维护的待办事项。 我想访问父TodoForm的状态,并从TodoFormhandleClick组件中添加一个新的待办事项。 我的想法是做父母的setState,这将呈现新添加待办事项。

在你的父类中,你可以创build一个像addTodoItem这样的函数,它将执行所需的setState,然后将该函数作为道具传递给子组件。

 var Todos = React.createClass({ ... addTodoItem: function(todoItem) { this.state.todos.push(todoItem); this.setState({todos: this.state.todos}); }, render: function() { ... return <div> <h3>Todo(s)</h3> {todos} <TodoForm addTodoItem={this.addTodoItem} /> </div> } }); var TodoForm = React.createClass({ handleClick: function(e) { e.preventDefault(); this.props.addTodoItem(this.state.todoInput); this.setState({todoInput: ""}); }, ... }); 

你可以在TodoForm的handleClick中调用addTodoItem 。 这将做父母的setState将呈现新添加待办事项项目。 希望你明白了。

在这里拨弄。

您可以在父组件中创build一个addTodo函数,将其绑定到该上下文,将其传递给子组件,并从那里调用它。

 // in Todos addTodo: function(newTodo) { // add todo } 

那么,在Todos.render,你会做的

 <TodoForm addToDo={this.addTodo.bind(this)} /> 

用TodoForm调用这个

 this.props.addToDo(newTodo); 

我发现下面的工作和简单的解决scheme,从一个子组件传递参数到父组件:

 //ChildExt component class ChildExt extends React.Component { render() { var handleForUpdate = this.props.handleForUpdate; return (<div><button onClick={() => handleForUpdate('someNewVar')}>Push me</button></div> ) } } //Parent component class ParentExt extends React.Component { constructor(props) { super(props); var handleForUpdate = this.handleForUpdate.bind(this); } handleForUpdate(someArg){ alert('We pass argument from Child to Parent: \n' + someArg); } render() { var handleForUpdate = this.handleForUpdate; return (<div> <ChildExt handleForUpdate = {handleForUpdate.bind(this)} /></div>) } } if(document.querySelector("#demo")){ ReactDOM.render( <ParentExt />, document.querySelector("#demo") ); } 

看看JSFIDDLE