从父组件,我传递给子组件comp handleOnChange功能,该功能应侦听Dropdown中的更改(来自React-SemanticUI)。

但是我在某个地方犯了错误。我得到了未定义的onChange事件侦听器值。

父母补偿:

   class AwwWrapper extends Component {
          state = {
            injuredWorkerType: '',
            totalDays: '',
          }

          onChangeInjuredWorkerType = event => {
            this.setState({ injuredWorkerType: event.target.value })
          }

          render() {
            return (
              <Segment
                raised
                style={{
                  backgroundColor: '#F0F0F0',
                }}
              >
              // HERE IS CHILD COMPONENT IN WHICH I PASS EVENT HANDLER
                <InjuredWorkerPayFields2
                  {...this.props}
                  onChangeInjuredWorkerType={this.onChangeInjuredWorkerType}
                  injuredWorkerType={this.state.injuredWorkerType}
                />
              </Segment>
            )
          }
        }

        export default AwwWrapper


儿童组件:

  return (
    <Form.Group widths={'equal'} style={{ marginTop: '2rem' }}>
      <Form.Field required width={5}>
        <label style={{ fontSize: '0.85rem' }}>2a. Injured worker type:</label>
        <Dropdown
          onChange={props.onChangeInjuredWorkerType}
          selection
          name={'injured_worker_type'}
          placeholder={'Worker Type'}
          options={workerTypeOptions}
          value={props.injuredWorkerType}
        />
      </Form.Field>
    </Form.Group>
  )
}

export default InjuredWorkerPayFields2


为什么我在这里得到未定义的值?

 `
 onChangeInjuredWorkerType = event => {
 this.setState({ injuredWorkerType: event.target.value })
}
 `

最佳答案

因为您要在此处将props.injuredWorkerType的值分配给DropDown value={props.injuredWorkerType}。因此props.injuredWorkerType将是未定义的。在父级组件中使用onChangeInjuredWorkerType似乎对您没有好处。因此,我建议您在子组件中声明处理程序函数,并在那里自行管理状态,而不要使用回调。

或者,如果您想要那样,请尝试以下解决方案

 <Dropdown
      onChange={props.onChangeInjuredWorkerType}
      selection
      name={'injured_worker_type'}
      placeholder={'Worker Type'}
      options={workerTypeOptions}
      value={props.injuredWorkerType ? props.injuredWorkerType : ""}
    />

08-08 02:16