【问题标题】:My select component dont't perform onChange (React.js)我的选择组件不执行 onChange (React.js)
【发布时间】:2021-03-17 12:19:59
【问题描述】:

我有一个默认执行 onChange 操作的 React Select 组件 (react-select.com)。我想要做的是设置另一个动作与第一个动作一起执行。

问题是:当我将一个函数传递给onChange 时,它会覆盖另一个函数。我尝试进行一些更改,但没有成功,所以我将在此处显示我的代码,而无需它们。

我的组件:

function SelectInput(props: any) {
const [field, defaultValue, {setValue}] = useField(props.field);

const handleChange = (value: any) => {
    setValue(value.value);
};

const {options} = props;

return (
    <Select
        styles={styles}
        className="react-select-container"
        classNamePrefix="react-select"
        options={options}
        name={field.name}
        onChange={handleChange}
        value={
            options
                ? options.find(
                      (option: any) => option.value === field.value
                  )
                : ''
        }
        {...props}
    />
);
}

我想如何使用它:

{
<Field // this comes from Formi
    name="type"
    component={SelectInput} // here I tell Formik to render my component, it works the same as rendering it directly
    placeholder=" "
    options={options}
    onChange={() => {MY_FUNCTION_HERE}} // I want to call this function and also the handleChange inside the component
/>
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这是因为您将 {...props} 作为最后一个 prop 传递给 Select 组件。因此,来自道具的 onChange 函数将覆盖您声明的函数。试试这个:

     <Select
            {...props}
            styles={styles}
            className="react-select-container"
            classNamePrefix="react-select"
            options={options}
            name={field.name}
            onChange={handleChange}
            value={
                options
                    ? options.find(
                          (option: any) => option.value === field.value
                      )
                    : ''
            }
        />
    

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 2021-11-28
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      相关资源
      最近更新 更多