[英]How to add required to react-select?
I'm using react-select library to add dropdown menu for my app, but "required" doesn't work (I read a discussion on GitHub for this library, creators haven't added that function yet), so for now how do I make select required?我正在使用 react-select 库为我的应用程序添加下拉菜单,但“必需”不起作用(我阅读了有关此库的 GitHub 的讨论,创建者尚未添加 function),所以现在该怎么做我需要 select 吗? (I read here another post with the same problem, solution presented there didn't work for me). (我在这里阅读了另一个有同样问题的帖子,那里提出的解决方案对我不起作用)。 My code is:我的代码是:
import React, { useState } from "react";
import Select from "react-select";
export default function App() {
const [data, setData] = useState();
const options = [
{ value: "1", label: "1" },
{ value: "2", label: "2" },
{ value: "3", label: "3" },
{ value: "4", label: "4" }
];
const handleSubmit = (e) => {
console.log(data);
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input required placeholder="name" />
<Select
options={options}
onChange={(e) => setData(e.value)}
value={options.filter(function (option) {
return option.value === data;
})}
label="Single select"
placeholder={"Select "}
menuPlacement="top"
required
/>
<button> Submit</button>
</form>
</div>
);
}
In my code I have a couple of regular inputs (where required works fine) but I want the Select also be required.在我的代码中,我有几个常规输入(在需要的地方可以正常工作),但我希望 Select 也是必需的。 Any suggestions are greatly appreciated.非常感谢任何建议。
I would think outside the box — in this case the Select component.我会跳出框框思考——在这种情况下是 Select 组件。 What can you add that gets the same result?你可以添加什么得到相同的结果? I took a quick stab at this for you:我为你做了一个快速的尝试:
const [isValid, setIsValid] = useState(false);
// This effect runs when 'data' changes
useEffect(() => {
// If there is data, the form is valid
setIsValid(data ? true : false);
}, [data]);
...
return (
<div>
<Select ... />
{!isValid && <p>You must choose a value</p>}
<button disabled={!isValid}>Submit</button>
</div>
)
https://codesandbox.io/s/vigilant-wiles-6lx5f https://codesandbox.io/s/vigilant-wiles-6lx5f
In this example, we check the state of the Select component — if it's empty (the user hasn't chosen anything) the form is invalid and the submit button is disabled.在这个例子中,我们检查 Select 组件的 state - 如果它是空的(用户没有选择任何东西),则表单无效并且提交按钮被禁用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.