通过子级按钮更新父级状态的正确方法

时间:2020-03-03 13:17:25

标签: javascript reactjs

我正在尝试绕过处理程序函数来更新子级的父级状态,但出现错误:

class Parent(){
  contractor(props){
    super(props);
    this.state = {
      answer: ""
    }
  };

  hanadleAnswer = _answer => {
    this.setState({ answer: _answer });
  }

  render () {
    return (
       <Switch>
         <Route path="questions" component={<Child handler={_answer => this.handleAnswer(_answer)}/>}
       </Switch>
    )
  }
}

在孩子中,我想根据发送的选项答案来更新答案的状态

function Child({ handler }){
  ... 
  <Button onClick={handler({option_1})}></Button> 
  <Button onClick={handler({option_2})}></Button> 
  ...
}

我意识到即使不单击按钮也会触发处理程序,并显示错误消息:

Unhandled Rejection (Error): Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

如果该方法不起作用,如何根据子bu按钮的值更新父状态?

1 个答案:

答案 0 :(得分:3)

像这样使用-

function Child({ handler }){
  ... 
  <Button onClick={()=>handler({option_1})}></Button> 
  <Button onClick={()=>handler({option_2})}></Button> 
  ...
}

参考,以更好地理解Handling Events 。从该页面引用:

将参数传递给事件处理程序

在循环内,通常要将一个额外的参数传递给事件处理程序。例如,如果id是行ID,则可以使用以下任意一种方法:

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>