如何在React-Select中使用setValue?

Fre*_*y31 3 react-select

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

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

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

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,这项工作中的所有元素均未注释。我可以检查该值是否被选择,如果是,我可以完全清除选择。

但现在我特别需要改变一些元素。但这是行不通的。该文档对此并没有多大用处。

在此输入图像描述

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

Fre*_*y31 7

好吧,这么小的修正。

hasValue('optionA')行只会告诉您该值是否存在。如果检查的话就不会。

您需要执行 agetValue()来获取所有选中的选项,然后进行搜索。

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