2017-08-10 152 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

相關問題