在子组件的父项上执行setState的推荐模式是什么?
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的handleClick组件中添加新的待办事项。我的想法是在父对象上执行setState,这将呈现新添加的待办事项。
TodoForm
handleClick
在您的父级中,您可以创建一个类似的函数addTodoItem,该函数将执行所需的setState,然后将该函数作为prop传递给子组件。
addTodoItem
var Todos = React.createClass({ ... addTodoItem: function(todoItem) { this.setState(({ todos }) => ({ todos: { ...todos, todoItem } })); }, 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: ""}); }, ... });
您可以addTodoItem在TodoForm的handleClick中调用。这将在父级上执行setState,它将呈现新添加的待办事项。希望你能明白。
在这里摆弄。