javascript - 从父组件修改子状态

标签 javascript reactjs

父组件在应用栏和绘图区中包含一个按钮(我在其中拖放了一些内容,这仅适用于此处的上下文)。 我想让子组件保持相对独立。

我想在单击此父组件中可用的按钮时更改子组件的状态。 当我使用不安全的“componentWillReceiveProps”时它起作用(并且替换功能“很少使用”。 所以我从来没有成功地从父组件调用函数(在子组件中)。

React 中的最佳实践是什么?(我来自 PHP/GO/Python 背景)。

父类:

Class EditionView extends React.Component {

  constructor(props) {
    super(props)
    var drawingModel = this.emptyDrawingModel();
    this.state= {drawingModel:drawingModel};
  }

  emptyDrawingModel(){
    var drawingModel = []
    for (var i=0; i<3; i++) {
      drawingModel.push('')
    }
    return drawingModel;
  }

  resetDrawingArea() {
    console.log("tmp:", this);
    var drawingModel = this.emptyDrawingModel();
    this.setState({drawingModel: drawingModel});
  }

  render() {
    console.log(this.state);
    return (
      <div>
        <AppBar position="static" color="primary">
          <Typography variant="h6" color="inherit">
              Title
          </Typography>
          <Toolbar>
            <Button variant='contained' component='span' onClick={()=>{this.resetDrawingArea()}}>Reset</Button>
          </Toolbar>
        </AppBar>
        <Grid container>
          <Grid item sm={9}>
            <DrawingArea id='drawing' initialModel={this.state.drawingModel}/>
          </Grid>
        </Grid>
      </div>
    );
  }

}

export default EditionView;

子类

class DrawingArea extends React.Component {

  constructor(props) {
    super(props)
    this.state = {content:props.initialModel};
    //this.reset = this.reset.bind(this); 
    //this.reset = this.reset();
  }

  /*
  //WORKs but UNSAFE
  componentWillReceiveProps(){
    console.log("componentWillMount", this)
    this.setState({content: this.props.initialModel});
  }
  */

  reset(){
    console.log('in Drawing Area > reset')
    var model = this.props.initialModel;
    this.setState({content:model})
  }

  render() {
    console.log("render drawing area", this)
    var items = this.state.content.map((val, i) =>{
      var item;
      if (val === ''){
        // code for if 
      } else {
        // code for else
      }
      return item;
    });

    return(
      <div id="main-area">
        <Grid container>{items}</Grid>
      </div>
    )
  }
}

export default DrawingArea;

最佳答案

使用getDerivedStateFromProps :

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

class DrawingArea extends React.Component {

    static getDerivedStateFromProps(props) {
         return {
            content: props.initialModel
         }
    }

  ...
}

关于javascript - 从父组件修改子状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087079/

相关文章:

javascript - meteor react 设计 - 嵌套组件 : function call

javascript - componentWillMount 中的 setState 不会反射(reflect)在 componentWillMount 中

javascript - 如何与 JQuery RGB 值进行比较?

javascript - 数组映射,将数组映射为数组的键

javascript - 如何动态更改数组中对象属性的键名

javascript - Firebase/Firestore : No document exists but it should

java - 日期的字符串解析、JSON Stringify 和 GSON 解析失败

javascript - 如何在 React Native 中设置 axios 的休息状态

javascript - 如何在 React/Redux 应用程序中刷新页面后保持登录状态

javascript - 重新加载组件的 React.JS 问题