如何在 React-Select 中使用 setValue?

How to use setValue in React-Select?

文档中没有太多关于如何在 react 中使用 setValue 函数的内容 select。

这是我的问题。在我的 multiselect 中,我有一些元素,如果 selected,就会使其他元素无效。或者当 2 个特定元素被 selected 时,第三个元素必须被 selected。

所以我做一个如果。我有一个参考,所以它看起来像这样:

if(selectInputRef.current){
    if(selectInputRef.current.select.hasValue('optionA')){
        selectInputRef.current.select.clearValue();
        //selectInputRef.current.select.setValue('optionB','deselect-option');
    }
    if(selectInputRef.current.select.hasValue('optionA') && selectInputRef.current.select.hasValue('optionC')){
        //selectInputRef.current.select.setValue('optionD','select-option');
    }
}

所以在这项工作中所有元素都没有注释。我可以检查该值是否为 selected,如果是,我可以完全清除 select。

但现在我需要特别更改元素。这是行不通的。文档在这方面并不是很有用。

那么我应该如何编写它才能使这条线起作用?

好的,这么小的更正。

hasValue('optionA') 行只会告诉您该值是否存在。如果选中则不会。

您需要执行 getValue() 以获取所有选中的选项,然后搜索它。

此外,setValue 设置 select 的完整值。不需要清除。它需要完整的数据阵列。所以 setValue([{value: 'optionA', label:'Option A'}]); 将选中该选项并取消选中其他所有内容。