如何在React语义下拉列表元素中侦听变化?

时间:2018-10-04 11:55:47

标签: javascript reactjs

我从父组件传递到child-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 })
}
 ` 

1 个答案:

答案 0 :(得分:1)

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

或者,如果您希望这样,请尝试以下解决方案

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