![](/img/trans.png)
[英]Clear Select component after an option is selected in Ant Design and React
[英]auto select onBlur in React JS using ant design Select component
我有以下代码
我正在尝试执行以下操作。 当用户在输入中输入内容时,它应该被添加到我的 onBlur 数组中。 那部分工作得很好。 现在除了添加到数组之外,我还希望它自动被选中。 我该如何实现呢?
import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "and";
const { Option } = Select;
const arr = ["1", "2", "3"];
const App = () => {
const [data, setData] = useState(arr);
return (
<>
<Select
mode="tags"
size={"large"}
placeholder="Please select"
style={{
width: "100%"
}}
>
{data?.map((el) => (
<Option key={el} value={el}>
{el}
</Option>
))}
</Select>
<input onBlur={(e) => setData([...data, e.target.value])} />
</>
);
};
export default App;
请帮我解决这个问题。
您需要控制Select
组件的children
项( data
)和value
。
您可以通过使用value
和onChange
道具来控制Select
组件的 state ,如下所示:
import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";
const { Option } = Select;
const arr = ["1", "2", "3"];
const App = () => {
const [data, setData] = useState(arr);
const [value, setValue] = useState([]);
const handleTextBlurred = (e) => {
const newVal = e.target.value;
if (!data.includes(newVal)) {
setData([...data, newVal]);
}
if (!value.includes(newVal)) {
setValue([...value, newVal]);
}
};
return (
<>
<Select
mode="tags"
size={"large"}
placeholder="Please select"
style={{
width: "100%"
}}
value={value}
onChange={(newVal) => setValue(newVal)}
>
{data?.map((el) => (
<Option key={el} value={el}>
{el}
</Option>
))}
</Select>
<input onBlur={handleTextBlurred} />
</>
);
};
export default App;
您可以查看这个分叉的沙箱,了解该解决方案的实时工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.