我正在構建一個回傳 Ant Design Select 下拉選單的可重用組件。我正在努力獲取該值,并將其設定為父組件中的狀態。
下面是下拉生成器。
import React from 'react';
import { Select } from 'antd';
const { Option } = Select;
// This function will generate a dropdown menu that will render from a list of options to be mapped. It also requires a changeHandle function to be passed in as a prop, likely to be used to set the state of the parent component.
const DynamicDropdown = ({ options, name, onChange, data, setaData }) => {
//options is an array of options to be mapped
//name is the name of the dropdown menu
//data is the state of the parent component
//setaData is the function to set the state of the parent component
return (
<Select
showSearch
name={name}
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
name={name}
>
{options.map(option => (
<Option value={option} onChange={onChange} name={name}>
{option}
</Option>
))}
</Select>
);
};
export default DynamicDropdown;
props 中發送的 data 和 setData 是下面的狀態。
const [formData, setFormData] = useState({
meeting_topic: '',
meeting_start_time: '',
meeting_end_time: '',
mentor_id: '',
mentee_id: '',
admin_meeting_notes: '',
mentor_meeting_notes: '',
mentee_meeting_notes: '',
});
資料選項道具如下。
const mentees = ['Mentee 1', 'Mentee 2', 'Mentee 3'];
onChange 道具是以下功能
const handleChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value });
console.log(formData);
};
知道我可能做錯了什么>?我在不同的地方嘗試過不同事物的多種組合。我似乎找不到太多關于將 Select 設定為狀態的檔案。謝謝!
嘗試將 changeHandel 直接移動到組件中,將名稱移動到不同的位置,包括在 returnedJSX 中。我什至通過直接在 dynamicDropdown 本身中設定狀態來破壞可重用性。
uj5u.com熱心網友回復:
您的 optins 資料結構無效。optoins 陣列應該是這樣的:
const options=[
{
value: 'jack',
label: 'Jack',
},
{
value: 'lucy',
label: 'Lucy',
},
{
value: 'disabled',
disabled: true,
label: 'Disabled',
},
{
value: 'Yiminghe',
label: 'yiminghe',
},
]
每個元素都應具有值和標簽以查看完整代碼單擊此處: 完整代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/537047.html
