如果没有触发 onChange 事件,有没有办法在 React-Selects Select 中获取当前值?
Is there a way to get current value in React-Selects Select if the onChange event has not fired?
我在我的代码中添加了一个 React-Select 组件,我在其中传递了 options 属性和 onChange 回调以获取那里的值。我需要做的是能够在用户按下将整个表单重置回其原始状态的按钮时将该值重置回 null。这就是为什么我觉得我需要一种方法来访问 select 的当前值,以便我可以将它设置回 null。
我试图将 ref prop 传递给 select 以获取那里的当前值,我在控制台中看到当我选择退出按钮时 currentValue 和 value 被设置回未定义。
<Select
title={'List'}
options={createListOptions}
ref={listSelectRef}
closeMenuOnSelect={true}
filterOption={createFilter({
matchFrom: 'start',
})}
isRequired
value={listId}
onChange={value => {
setListIds(value);
setListError(false);
}}
error={listError}
/>
</div>```
单击按钮后,您可以使用 ref
、
获得 selected 值
<Select defaultValue={options[1]} options={options} ref={this.listSelectRef}/>
<button onClick={this.getVal}>Get Value</button>
这里defaultValue
用于初始值,这样我们可以在不改变select值的情况下检查如何得到已经select的值。
你的功能应该是,
getVal = () =>{
console.log(this.listSelectRef.current.state.value); //this will give you selected option object
console.log(this.listSelectRef.current.state.value.value); // this will give you value
console.log(this.listSelectRef.current.state.value.label); //this will give you label which is actually shown on front end
}
我认为你应该为此尝试 AsyncSelect
我在我的代码中添加了一个 React-Select 组件,我在其中传递了 options 属性和 onChange 回调以获取那里的值。我需要做的是能够在用户按下将整个表单重置回其原始状态的按钮时将该值重置回 null。这就是为什么我觉得我需要一种方法来访问 select 的当前值,以便我可以将它设置回 null。
我试图将 ref prop 传递给 select 以获取那里的当前值,我在控制台中看到当我选择退出按钮时 currentValue 和 value 被设置回未定义。
<Select
title={'List'}
options={createListOptions}
ref={listSelectRef}
closeMenuOnSelect={true}
filterOption={createFilter({
matchFrom: 'start',
})}
isRequired
value={listId}
onChange={value => {
setListIds(value);
setListError(false);
}}
error={listError}
/>
</div>```
单击按钮后,您可以使用 ref
、
<Select defaultValue={options[1]} options={options} ref={this.listSelectRef}/>
<button onClick={this.getVal}>Get Value</button>
这里defaultValue
用于初始值,这样我们可以在不改变select值的情况下检查如何得到已经select的值。
你的功能应该是,
getVal = () =>{
console.log(this.listSelectRef.current.state.value); //this will give you selected option object
console.log(this.listSelectRef.current.state.value.value); // this will give you value
console.log(this.listSelectRef.current.state.value.label); //this will give you label which is actually shown on front end
}
我认为你应该为此尝试 AsyncSelect