簡體   English   中英

React select 設置初始值 Redux Form

[英]React select set initial value with Redux Form

我正在嘗試使用 Redux 表單字段為我的 Select 標簽設置一個初始值。

Redux 字段:

<Field
                    name="statusDto.pkid"
                    component={renderSelectField}
                    type="text"
                    isHidden="true"
                    placeholder="Select Status"
                    options={userRegistrationStatus && userRegistrationStatus.map((values) => { return ({ value: values.pkid, label: i18next.languages[0] === 'en' ? values.enName : values.trName }); })}
                  />

Redux 表格:

UserRegistrationForm = reduxForm({
  validate,
  form: 'User_Registration_Form', // a unique identifier for this form
  enableReinitialize: true,
})(UserRegistrationForm));

反應 Select:

handleChange = (selectedOption) => {
    const { onChange } = this.props;
    this.setState({ selectedOptionState: selectedOption });
    onChange(selectedOption.value);
  };

 <Select
        name={name}
        value={selectedOptionState}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />

使用 redux-form initialize,我嘗試將第一個值分配給 react-select,但這似乎不值得。 你能幫助我嗎?

我解決了這個問題。

反應選擇:

<Select
        name={name}
        value={(value === '') ? null : options.find(obj => obj.value === value)}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />

在你的 RenderSelectField 組件上用{label:"LABELX", value: "ValueY"}初始化你Select組件的 redux RenderSelectField字段添加一個應該映射到從props.input收到的屬性的屬性值

const RenderSelectField =(props) => {

  // Complete the seleect component with your additional props
  return (
    <Select
      value={props.input.value}
    />
  );
}

因為該valueoptions數組的一個元素。 你不需要寫一個find function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM