代码之家  ›  专栏  ›  技术社区  ›  four-eyes

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

  •  3
  • four-eyes  · 技术社区  · 8 年前

    有没有办法设置 state Component Props 这个 从接收 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 回复  |  直到 8 年前
        1
  •  2
  •   flaky    8 年前

    正如马扬克·舒克拉(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' });
    }
    
        2
  •  0
  •   bluehipy    8 年前

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

    this.state = {
         title: 'Some title',
         // other local stateful attributes
         children:{
            kidId1:{
              kidAttr1:' 'value'
            },
            ....
            kidId100:{
              kidAttr1:' 'value'
            }
         }
    };
    
    推荐文章