[英]onChange react-select not calling my function
I have the following react-select code which all works fine and sets my Formik state values.我有以下反应选择代码,它们都可以正常工作并设置我的 Formik state 值。
const [selectedOptions, setSelectedOptions] = useState([]);
<Select
options={myOptions}
isMulti={true}
name={`myGroups.${index}.selectedOptions`}
onChange={(selectedOptions) => {
let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOptions } };
handleChange(e);
handleChangeIndex(index);
}}
/>
My question is, during the onChange
I also want to call another function: handleChangeIndex
to set state values, ie:我的问题是,在
onChange
期间,我还想调用另一个 function: handleChangeIndex
来设置 state 值,即:
const handleChangeIndex = index => selectedOption => {
console.log("inside handleChangeIndex....")
const optionsCopy = [...selectedOptions];
optionsCopy[index] = selectedOption;
setSelectedOptions(optionsCopy);
};
In my <Select>
above, my function handleChangeIndex(index)
is not being called as I am not seeing a console.log message but if I call the <Select>
as follows with just my handleChangeIndex
alone it works.在我上面的
<Select>
中,我的 function handleChangeIndex(index)
没有被调用,因为我没有看到 console.log 消息,但是如果我只使用我的handleChangeIndex
如下调用<Select>
它就可以工作。
<Select
options={myOptions}
isMulti={true}
name={`myGroups.${index}.selectedOptions`}
onChange={handleChangeIndex(index)}
/>
Can people pls assist with how to call my function as in the top <Select>
人们可以协助如何在顶部
<Select>
中调用我的 function
When you pass handleChangeIndex
into Select
directly, you are calling the function, which is returning another function ( currying ).当您将
handleChangeIndex
直接传递给Select
时,您正在调用 function,它返回另一个 function(柯里化)。 Then Select
is calling that new inner function when the values change.然后
Select
在值更改时调用新的内部 function 。
When you call handleChangeIndex
directly in the onChange
in the first example you gave, you are only calling it once, which means you are getting that inner function, and then doing nothing with it.当您在给出的第一个示例中直接在
onChange
中调用handleChangeIndex
时,您只调用了一次,这意味着您将获得内部 function,然后什么也不做。
If you then call that inner function with the selectedOptions
, then it should work fine.如果您随后使用
selectedOptions
调用该内部 function ,那么它应该可以正常工作。
const [selectedOptions, setSelectedOptions] = useState([]);
<Select
options={myOptions}
isMulti={true}
name={`myGroups.${index}.selectedOptions`}
onChange={(selectedOptions) => {
let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOptions } };
handleChange(e);
handleChangeIndex(index)(selectedOptions);
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.