使用父组件的道具设置状态

时间:2017-08-10 10:03:12

标签: javascript reactjs react-native state

有没有办法在state中设置Component 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);
        ...
    }
}

2 个答案:

答案 0 :(得分:2)

正如Mayank Shukla所说,将父道具存放在孩子的状态是不好的做法,从而管理孩子的状态。

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

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

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

// 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' });
}

答案 1 :(得分:0)

建议将孩子状态保留在父组件中。因此children最终会包含this.state = { title: 'Some title', // other local stateful attributes children:{ kidId1:{ kidAttr1:' 'value' }, .... kidId100:{ kidAttr1:' 'value' } } }; 部分,其中的孩子状态可以存储在唯一ID中。

{{1}}
相关问题