Monday, 15 September 2014

ReactJS: setState on parent inside child component -


What is the recommended pattern to setState on a child component from a child component. Var Todos = React.createClass ({getInitialState: function () {Returns {todos: ["I did", "I did not do"]}}, render: function () { Var todos = this.state.todos .map (function (to work) {return

gt; {doing}}
;}}; return
gt; & lt; div & gt; Lt; h3 & gt; Todo (s) & lt; / h3 & gt; {all} & lt; TodoForm / & gt; & lt; / div & gt ;;}}); On TodoForm = React.createClass ({getInitialState: function () {return {todoInput: ""}}, handleOnChange: function (e) {e.preventDefault (); this.setState ({todoInput: e.target.value}) ;};), HandleClick: function (e) {e.preventDefault (); // Add new todo item}, render: function () {Return & Lt; Button onClick = {} this.handleClick & gt; / Button & gt; Add to Todo & lt & lt; / Div>;}}}; reaction. Render (, document.body)

I have an array of palm material that is kept in the parental state. I want to use parental status and want to add a new toy item from the TodoForm to handleClick component. My idea is to have a setstate on the parent, who will present the newly added item.

In your parents, you can create functions such as addTodoItem Which will do the necessary setstate and then will organize that function as the child component.

var Todos = React createClass ({... addTodoItem: function (todoItem) {this.state.todos.push (todoItem); this.setState ({all: this.state.todos });}, Render: function () {... return

todo (s) {all} & lt; TodoForm addTodoItem = {This.addTodoItem} /> & lt; / div & gt;}}); On TodoForm = React.createClass ({handleClick: Function (e) {e.preventDefault (); this.props.addTodoItem (this.state.todoInput); this.setState ({todoInput: ""});} .. });

You can open addTodoItem in TodoForm's handleClick. This will set a set on parents who will present the newly added item. Hope you get this idea.


No comments:

Post a Comment