如何传递状态值作为道具并将其设置为子级?

时间:2019-12-29 20:16:05

标签: reactjs react-native

我有一个子组件,我在其中从父级传递状态,然后我想更新父级状态。

我在父组件中这样称呼孩子:

<ReminderButton
   buttonDisabledState={this.state.oneDayButtonDisabled}
   addReminderFunction={this.props.defaultHomeworkReminder(item, 'oneDay', 1)}
/>

然后在子项中按如下所示更新按钮按下状态:

onPress={() => {
  this.setState({ [props.buttonDisabledState]: true });
  setTimeout(() => this.setState({ [props.buttonDisabledState]: false }), 1500);
  if (props.isReminderActive === false && moment(new Date()).isBefore(props.item.date)) {
      props.addReminderFunction();
  }
}

我收到未定义setState的错误。

3 个答案:

答案 0 :(得分:1)

在父组件中创建一个函数来更新状态,因为父组件会处理状态。

handlePress = value => {
    this.setState({ buttonDisabledState: value });
}

将此功能作为道具传递给子组件

<ReminderButton
   pressHandler={this.handlePress}
   addReminderFunction={this.props.defaultHomeworkReminder(item, 'oneDay', 1)}
/>

在子组件中,像这样使用它

onPress={() => {
  props.pressHandler(true);
  setTimeout(() => props.pressHandler(false), 1500);
  if (props.isReminderActive === false && moment(new Date()).isBefore(props.item.date)) {
      props.addReminderFunction();
  }
}

请注意setState()调用是异步的,并且可能会使用状态的新值(认为您已经调用了setState())而没有实际更新这可能会导致不太容易识别的问题。

答案 1 :(得分:1)

您不能直接在子组件中设置父组件的状态,但是可以给子组件一个回调函数作为属性:

<ReminderButton
   buttonDisabledState={this.state.oneDayButtonDisabled}
   updateParentState={this.onSetStateFromChildComponent.bind(this)}
   addReminderFunction={this.props.defaultHomeworkReminder(item, 'oneDay', 1)}
/>

然后是父元素中的函数:

public onSetStateFromChildComponent(newState){
   this.setState(() => newState); 
}

问候!

答案 2 :(得分:0)

默认情况下,Ok react允许从父母到子组件传递数据或状态,如果您需要从子到父母,则有一些选项可以使用Redux或Mobx来管理状态,但是如果您不安装任何选项第三方库,您必须使用上下文API或使用函数来处理此问题,这是一个小例子

我们有一个父组件,该组件包装了一个计数器组件,并且有一个名为“ changeScore”的道具,该道具接收一个handleScore函数(句柄得分改变状态,使状态加1)

state = {counter: 0};

handleScore(i) {
  this.setState(state => ({
    counter: state.counter + i
  }))
};



render(){
  return (
    <div className="scoreboard">
      <Counter
        changeScore={this.handleScore}
      />
    </div>
  )
}

这是Counter组件,当用户单击按钮时,该组件使用ChangeScore道具对其进行射击

const Counter = ({changeScore})=>{
return(
    <div className="counter">
        <button
            onClick={
                ()=>{changeScore(1)}
            }
            >+</button>
    </div>
);};