我想让用户能够添加自定义文本,如果他们认为适合的选择不在选择选项中显示的那些。我已经成功地创建了自定义文本字段,但是获取用户输入并将其设置为选择组件的值正在成为一种痛苦(听起来很容易做到,但由于某种原因,它不工作)这是我的实现
const [selectedpurpose, setSelectedPurpose] = useState<string>("");// selected value of the select component
const [customOption, setCustomOption] = useState<string>("");//custom userinput
const [dropoptions, setDropOptions] = useState([
{ value: "General Meeting", label: "General Meeting" },
{ value: "Consultation Meeting", label: "Consultation Meeting" },
{ value: "AdCampaign Meeting", label: "Ad Campaign Meeting" },
{ value: "Marketing Meeting", label: "Marketing Meeting" },
]);//select options
// function to recored custom user input
const handleAddOption = () => {
if (customOption) {
const newOption = { value: customOption, label: customOption };
setDropOptions([newOption, ...dropoptions]);
setSelectedPurpose(customOption);
setCustomOption("");
}
};
//my form
<Form.Item
name="purpose"
label="Purpose of Visit"
rules={[
{
required: true,
message: "Please select Purpose of Visit!",
},
]}
>
<Select
defaultActiveFirstOption={false}
value={selectedpurpose}
onChange={(e) => {
if (customOption) {
setSelectedPurpose(customOption);
}else{
setSelectedPurpose(e)
}
}}
dropdownRender={(menu) => (
<div>
{menu}
<div
style={{
display: "flex",
flexWrap: "nowrap",
padding: 8,
}}
>
<Input
style={{ flex: "auto" }}
maxLength={20}
value={customOption}
onChange={(e) => {
if (e.target.value.length > 20) {
// if user has reached the maximum length
// show a message or change the color of the input to indicate the limit has been reached
// for example:
openNotificationWithIcon(
"error",
"Warning",
"Maximum length reached!"
);
} else {
setCustomOption(e.target.value);
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
handleAddOption();
}
}}
/>
<Button
type="link"
onClick={handleAddOption}
style={{ flex: "none", padding: "0px 4px" }}
>
Add
</Button>
</div>
</div>
)}
>
{dropoptions.map((option) => (
<Option key={option.value} value={option.value}>
{option.label}
</Option>
))}
</Select>
</Form.Item>
我做错了什么,根据我的代码单击添加按钮按钮和按enter应该添加新的值到选项数组,以及选择用户输入作为选择组件的值,但到目前为止,它只会将其添加到选项数组,并忽略将其设置为选择值任何帮助都是感激的
try this one
import React from "react";
import "./styles.css";
import Select, { components } from "react-select";
const CustomInput = (props) => {
const { maxLength } = props.selectProps;
const inputProps = { ...props, maxLength };
return <components.Input {...inputProps} />;
};
const App = () => {
const options = [
{ label: "Option 1", value: 1 },
{ label: "Option 2", value: 2 },
{ label: "Option 3", value: 3 }
];
return (
<Select
options={options}
components={{ Input: CustomInput }}
maxLength="4"
/>
);
};
export default App;