通过道具

时间:2017-05-22 17:08:20

标签: reactjs jsx

我想通过一个函数来更新状态,我通过onChange属性通过props传递给子组件。这是在子组件中:

<input className="minutes" type="number" defaultValue={ this.props.minutes } onChange={ this.props.updatePreferences("minutes", this.value) }/> minutes. 

虽然这是父组件中的函数:

  updatePreferences = (preferenceName, enteredValue) => {
     switch (preferenceName) {
      case preferenceName === "minutes":
        this.setState({minutes: enteredValue})
        console.log(this.state)
        return
      case preferenceName === "business":
        this.setState({...this.state, interests: {
          ...this.state.interests, business: !this.state.interests.business}})
        return
      default:
        return
    }
  }

然后通过路线传递给孩子:

<Route exact path="/" render={props => <Welcome minutes = {this.state.minutes} 
                                                          interests = {this.state.interests}
                                                          sayHello = {this.sayHello} 
                                                          updatePreferences = {this.updatePreferences} />} />

2 个答案:

答案 0 :(得分:0)

defaultValue仅在安装期间设置,因此在重新渲染时无法更改。 (除非您使用ref更新。)

此外,您不希望在渲染时调用updatePreferences方法,因此您需要bind或使用箭头功能。

使用value prop来创建受控组件:

<input className="minutes"
       type="number"
       value={ this.props.minutes } onChange={ () => this.props.updatePreferences("minutes", this.value) }/> minutes. 

答案 1 :(得分:0)

使它成功的两件事:

(e) => this.props.updatePreferences("minutes", e.target.value)

并且switch语句的语法错误:

 switch (preferenceName) {
  case "minutes":
    this.setState({minutes: enteredValue})
    return
  case "business":
    this.setState({...this.state, interests: {
      ...this.state.interests, business: !this.state.interests.business}})
    return
  default:
    return
}