如何将父状态传递给它的子组件? [英] How do I pass parent state to its child components?

查看:95
本文介绍了如何将父状态传递给它的子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React ES6的新手,我认为我以错误的方式修改了状态.当我在父组件上设置状态时,我的代码是这样的:

I am new in React ES6 and I think I am modifying the state in a wrong way. My code is like this when I set state on 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  
  ); 
 } 
}

我的问题是在其他子组件中,我必须重复执行此操作,还有另一种方法吗?我对React.createClass没问题,但是我想在es6中编码,所以我遇到了这个问题.

My problem is in other child components, I have to do it repeatitively, is there another way of doing it? I have no problem with React.createClass, but I want to code in es6 so i have this problem.

推荐答案

如果您想通过状态{name:"helloworld"},请按照以下步骤操作:

If you wanna pass the state {name:"helloworld"} do it like that:

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 props of the component to it's child:

   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 parent component from the child component you will need to pass a 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)} />
     ); 
    } 
  }

,然后在子组件中可以使用:this.props.update('new name')

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

更新

使用更多的es6并删除构造函数

use more es6 and removed 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} />
     ); 
    } 
  }

这篇关于如何将父状态传递给它的子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆