选项React Select中的可选字段

时间:2018-07-17 09:16:59

标签: reactjs redux-form react-select

嘿,我正在尝试与redux-form合作创建自动提示。我正在使用Creatable方法。我通过外部API加载我的选项。问题是,我在每个选项对象中都需要一个额外的字段。 {value: "test@gmx.de", label: "test@gmx.de", dn:"CN...." }。有可能这样做吗?

2 个答案:

答案 0 :(得分:0)

通常在将状态设置为选项之前,我通常在API请求的回调中添加自己的属性。例如...

    axios.get('/some/api/request')
    .then(response => {

        const options = response.data.map(item => {
            // Add whatever custom properties you want here
            return ({value: "test@gmx.de", label: "test@gmx.de", dn:"CN...." })
    }) 

    // set your options in the state to the new options constant from above
    dispatch(change('formName', 'options', options))

希望这会有所帮助!

答案 1 :(得分:0)

//Handle change with either selectedOption
  handleChange(selectedOption){
    this.setState({ selectedOption })
    if(this.props.onOptionSelect){
      this.props.onOptionSelect(selectedOption.data)
    }
  }

  loadOptions(input, callback) {
    this.props.loadOptions(input).then(options => {
      callback(null, {options: options})
    })
  }

  render() {
    const {selectedOption} = this.state
    const selectClass = this.props.meta.touched && this.props.meta.error ? "has-error form-group" : "form-group"
    return (
      <div className={selectClass}>
        <AsyncCreatable
          value={selectedOption}
          onChange={this.handleChange}
          loadOptions={this.loadOptions}
          isLoading={false}
          placeholder={this.props.label}
          promptTextCreator={(label) => this.props.promtLabel(label)}
          onBlur={() => this.props.input.onBlur(selectedOption.value || "")}
        />
      </div>
    )
  }


//Function to convert incomming users in usable options (React Select)
export const convertADUsersToOptions = users => {
  return users.map(user => {
    return {
      value: normalizeDN(user.dn),
      label: user.mail
    }
  })
}