繁体   English   中英

如何在单击提交时或第一次加载时设置默认选定值 - React Hook

[英]How to set the default selected value while clicking on submit or very first time while loading - React Hook

这是我的类别 state

const [category, setCategory] = useState('');

这是表单元素:

 <select onChange={e => setCategory(e.target.value)}>
                                        <Options options={categoryList} value={category}/>
                                        </select>

在更改值时,我正在选择类别

const handleBusinessInfoSubmit = (e) => {
        try{
            e.preventDefault();
            console.log("category selected is " +category);

        }
        catch{
            console.log("something went wrong!");
        }
    } 

当用户不更改值并点击提交时,如何设置类别 state?

作为参考,这里是类别列表,稍后将在键值对中以动态形式出现

 const categoryList = [
        {
            id: 1,
            value: 'Public Services'
        }, {
            id: 2,
            value: 'Automotive'
        }
        ];
// generate select dropdown option list dynamically
function Options({ options }) {
    return (
        options.map(option => 
                    <option key={option.id} value={option.value}>                                   
                    {option.value}
                    </option>)
                   );
        }

可能我会将默认初始值添加到useState而不是''

const [category, setCategory] = useState(categoryList[0]);

或者,如果数据是动态来的,那么使用 API 结果中的值调用setCategory() ,结果是您希望拥有的默认值。

我希望这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM