【问题标题】:Is there a way to reset the select field to the first value of array after click on a button?单击按钮后,有没有办法将选择字段重置为数组的第一个值?
【发布时间】:2022-11-01 23:35:52
【问题描述】:

我想创建一个选择输入,其中值始终重置为选项数组的第一个值

import Select from 'react-select';
import {useState} from 'react';
function Component(){

    const options = [{value: "something", label: "Something"}, ...]
    const [inputValue, setInputValue] = useState("");
    const [inputValue2, setInputValue2] = useState("");
    

    return (
        <div>
        <Select 
        options={options}
        onChange={(e) => setInputValue(e.value)}
        value={inputValue}
        />
        <Select 
        options={options}
        onChange={(e) => setInputValue2(e.value)}
        value={inputValue2}
        />
        <button onClick={handleReset}>Clear all Values</button>
        </div>
    )
}

单击按钮时,选择字段的所有值都应重置为选项数组的第一个值,我该如何实现?

这对我来说真的很重要。

【问题讨论】:

    标签: javascript reactjs react-hooks react-select


    【解决方案1】:

    您可以设置它,如果它没有选择,那么将选择数组的第一个值。 handleReset 函数实质上将值重置为空字符串,在这种情况下,选择字段将退回到数组的第一个值。

    注意:这也应该在页面加载之前将选择字段设置为第一个值。

    import Select from 'react-select';
    import {useState} from 'react';
    function Component(){
    
        const options = [{value: "something", label: "Something"}, ...]
        const [inputValue, setInputValue] = useState("");
        const [inputValue2, setInputValue2] = useState("");
        
        const handleReset = () => {
           setInputValue("");
           setInputValue2("");
        }
    
        return (
            <div>
            <Select 
            options={options}
            onChange={(e) => setInputValue(e.value)}
            value={inputValue || options[0].value}
            />
            <Select 
            options={options}
            onChange={(e) => setInputValue2(e.value)}
            value={inputValue2 || options[0].value}
            />
            <button onClick={handleReset}>Clear all Values</button>
            </div>
        )
    }
    

    【讨论】:

    • 我试过这个,它不起作用,值被重置但选择字段仍然具有与以前相同的值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多