有沒有一種方法來設置一個Component
的state
與Props
的Component
從Parent 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);
...
}
}
第一它不是存儲在子組件的狀態,所有的道具價值的一個很好的做法,以此來解決問題:'this.state = props' –
@MayankShukla我想我需要更多的代碼來了解什麼你意思是。我需要將道具從父組件傳遞給子組件,因爲子組件中的某個功能需要從父組件中處理道具以便呈現其本身(列表,...)。但是,對於更多的行爲,我需要將parend組件中的道具寫入child' this.state = {keyName:props.keyName}的構造函數內的子組件 – Stophface
的狀態'現在,父項中的keyName中的數據將被存儲在子組件的狀態。 –