简体   繁体   English

我的 select 组件不执行 onChange (React.js)

[英]My select component dont't perform onChange (React.js)

I have a React Select component (react-select.com) that by default performs a onChange action.我有一个 React Select 组件(react-select.com),默认情况下执行onChange操作。 What I want to do is to set another action to be executed along with the first one.我想要做的是设置另一个动作与第一个动作一起执行。

The problem is: when I pass a funtion to onChange , it overrides the another one.问题是:当我将一个函数传递给onChange时,它会覆盖另一个函数。 I tried to do some changes but it didn't work, so I will show my code here without them.我试图做一些改变,但没有奏效,所以我将在这里展示我的代码,没有它们。

My component:我的组件:

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}
    />
);
}

How I want to use it:我想如何使用它:

{
<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
/>
}

This is because you are passing {...props} to the Select component as the last prop.这是因为您将 {...props} 作为最后一个 prop 传递给 Select 组件。 So the onChange function coming from the props will override the one you declared.因此,来自道具的 onChange function 将覆盖您声明的那个。 Try this:尝试这个:

 <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
                  )
                : ''
        }
    />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM