有没有一种方法来设置一个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中的数据将被存储在子组件的状态。 –