这里的反应初学者,英语不是我的母语所以很抱歉有错误,这里我有一个输入,按钮和下拉(选择选项),'value'代表id和'text'代表customer,这里我有一个问题,当用户点击customer'james'(我有两个)它会选择这两个,如何纠正它应该选择点击的那个?如果没有同名用户,则所有操作都正常,我的代码:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Button, AutoComplete } from "antd";
import { CloseOutlined } from "@ant-design/icons";
export default function EventsSection() {
const autoControl = React.createRef();
const defaultOptions = [
{ value: "1", text: "Nicholas" },
{ value: "2", text: "Alex" },
{ value: "3", text: "Putin" },
{ value: "4", text: "Biden" },
{ value: "5", text: "Peka" },
{ value: "6", text: "James" },
{ value: "7", text: "James" }
];
const [options, setOptions] = useState(defaultOptions);
const [selectedOption, setSelectedOption] = useState("");
const [dropdownOpen, setDropdownOpen] = useState(true);
const [selectedValue, setSelectedValue] = useState("");
const { Option } = AutoComplete;
const changeHandler = (text) => {
setSelectedOption(text);
if (options.filter((f) => f.text === text).length) {
setSelectedValue(options.filter((f) => f.text === text)[0].value);
} else {
setOptions(defaultOptions);
setSelectedValue("");
}
if (!text || !text.length) {
setDropdownOpen(false);
autoControl.current.blur();
}
};
function handleClick() {
const id = selectedValue;
console.log(`value: ${id}, text: ${selectedOption}`);
//history.push(`/customer/${id}`);
}
function onClear() {
changeHandler("");
}
function onFocusChange() {
if (!dropdownOpen) setDropdownOpen(true);
}
function onSearch(value) {
setOptions(
defaultOptions.filter((f) =>
f.text.toLowerCase().includes(value.toLowerCase())
)
);
}
return (
<div>
{/* when found in search i want this button take to 'onChange' address also*/}
<button disabled={!selectedValue} onClick={handleClick}>
click me when found in search
</button>
<AutoComplete
ref={autoControl}
open={dropdownOpen}
style={{ width: 200 }}
placeholder="Search..."
listHeight={220}
onSearch={(e) => onSearch(e)}
onChange={changeHandler}
value={selectedOption}
onFocus={onFocusChange}
>
{options.map((option) => (
<Option key={option.value} value={option.text}>
{option.text}
</Option>
))}
</AutoComplete>
<Button
disabled={!selectedValue}
onClick={onClear}
type="primary"
icon={<CloseOutlined />}
/>
</div>
);
}
ReactDOM.render(<EventsSection />, document.getElementById("container"));
嘿,所以,为了解决这个问题,我认为您需要做的只是将选项组件的值设置为选项列表中的唯一键。
例如:
<Option key={option.value} value={option.value}>
{option.text}
</Option>
目标应该是让您的自动完成显示option.text
,但根据option.value
设置值和状态。