How to pass parent state to its child components?

I am new to React ES6 and I think I am changing the state incorrectly. My code looks like this when I set the state to the parent component:

class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } render() { return( <ChildComponent parentObj={this} /> // parentObj for parent context as props on child components ); } } 

My problem is with other child components, I have to do it repeatedly, is there any other way to do this? I have no problem with React.createClass, but I want code in es6, so I have this problem.

+13
source share
2 answers

If you want to pass the state {name: "helloworld"}, do it like this:

 class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } render() { return( <ChildComponent {...this.state} /> ); } } 

and in the child component you can do:

 <Text>{this.props.name}</Text> 

But if you want to pass the component details to this descendant:

  class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } render() { return( <ChildComponent {...this.props} /> ); } } 

and in the child component you can do:

 <Text>{this.props.stuff}</Text>//place stuff by any property name in props 

Now, if you want to update the state of the parent component from the child component, you will need to pass the function to the child component:

  class App extends React.Component { constuctor(props) { super(props); this.state = {name:"helloworld"}; } update(name){ this.setState({name:name})// or with es6 this.setState({name}) } render() { return( <ChildComponent {...this.props, update: this.update.bind(this)} /> ); } } 

and then in the child component you can use this: this.props.update('new name')

UPDATE

use more es6 and remote constructor

 class App extends React.Component { state = {name:"helloworld"}; // es6 function, will be bind with adding .bind(this) update = name => { this.setState({name:name})// or with es6 this.setState({name}) } render() { // notice that we removed .bind(this) from the update return( //send multiple methods using ',' <ChildComponent {...this.props, update = this.update} /> ); } } 
+18
source

if you want to send an integer state:

 return( <ChildComponent {...this.state} /> ); 

But this is probably a bad idea :)

edit: in your script, this sends the 'name' property to the child component with the value 'helloworld'

0
source

Source: https://habr.com/ru/post/1262880/


All Articles