2017-08-10 147 views
2

有没有一种方法来设置一个ComponentstatePropsComponentParent Component?从父组件道具设置状态

export default class SomeComp extends Component { 
    constructor(props) { 
     super(props); 

     this.state = someProps; // <-- I need the props to be the state of the Component 
    } 


    render() { 
     const { someProps } = this.props; 
     ... 
    } 
} 

接收或者,我可以写一个函数,像

export default class SomeComp extends Component { 
    constructor(props) { 
     super(props); 

    } 

    _setProps = (someProps) => { 
      this.State = someProps; 
    } 

    render() { 
     const { someProps } = this.props; 
     this._setProps(someProps); 
     ... 
    } 
} 
+1

第一它不是存储在子组件的状态,所有的道具价值的一个很好的做法,以此来解决问题:'this.state = props' –

+0

@MayankShukla我想我需要更多的代码来了解什么你意思是。我需要将道具从父组件传递给子组件,因为子组件中的某个功能需要从父组件中处理道具以便呈现其本身(列表,...)。但是,对于更多的行为,我需要将parend组件中的道具写入child' this.state = {keyName:props.keyName}的构造函数内的子组件 – Stophface

+2

的状态'现在,父项中的keyName中的数据将被存储在子组件的状态。 –

回答

2

由于Mayank舒克拉提到的,它是不好的做法,存储在一个孩子的状态父道具,从而管理孩子中的状态。

将道具传递给孩子的整个想法是,你不需要关心孩子的状态,因为这一切都是从父母那里流下来的。

子组件应该只关心它们的状态。

你应该做什么而不是做什么(以及什么是良好的反应练习)是在父组件中拥有状态并将事件处理程序传递给将改变父项状态的子项。

// in parent 
class MyParentComponent extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     data: someData; 
    }; 
    } 

    handleChange(data) { 
    this.setState(data); 
    } 

    render() { 
    return (
     <MyChildComponent 
     data={this.state.data} 
     handleChange={this.handleChange} 
     /> 
    ); 
    } 
} 



class MyChildComponent extends React.Component { 
    // this is going to update the data in parent 
    // and trickle it back down to the child 
    this.props.handleChange({ foo: 'bar' }); 
} 
0

建议将孩子们的状态保留在父组件中。所以parent.state最终将包含children部分,其中的孩子状态可以存储在唯一的ID下。

this.state = { 
    title: 'Some title', 
    // other local stateful attributes 
    children:{ 
     kidId1:{ 
      kidAttr1:' 'value' 
     }, 
     .... 
     kidId100:{ 
      kidAttr1:' 'value' 
     } 
    } 
}; 
+0

我将如何从父组件的子项访问道具? – Stophface

+0

父应该获取孩子状态并将其传递给孩子构造函数。 – bluehipy

相关问题