总是在反应 js antd 中的 select 下拉列表顶部显示 select 选项
always display select option on top of select dropdown list in react js antd
在 select 下拉菜单中我添加了默认选项值“--select--”。目前它显示在 select 列表的底部。我想把它显示在列表的顶部。请帮助我如何实现这一目标。
在沙箱中我添加了代码。请找到 link:
https://codesandbox.io/s/recursing-albattani-xdeud?file=/src/App.js
分量:
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Form, Select } from "antd";
import CollegeList from "./CollegeList";
const { Option } = Select;
const App = () => {
const [collegesList, setCollegesList] = React.useState(CollegeList);
const [collegesSelectedList, setCollegesSelectedList] = React.useState([]);
useEffect(() => {
const defaultState = {
name: "--select--"
};
setCollegesList([...collegesList, defaultState]);
console.log("initial load");
}, []);
const onFinish = (values) => {
console.log("Received values of form: ", values);
};
return (
<Form name="validate_other" onFinish={onFinish}>
<Form.Item name="select" label="Select">
<Select
placeholder="Please select a country"
onChange={(college) => {
setCollegesSelectedList([
...collegesSelectedList,
collegesList[college].name
]);
}}
>
{Object.keys(collegesList).map((college) => (
<Option value={college}>{collegesList[college].name}</Option>
))}
</Select>
</Form.Item>
</Form>
);
};
export default App;
目前它显示在下拉列表的底部。
只需更新您的 setCollegesList 如下:
setCollegesList([defaultState, ...collegesList]);
console.log("initial load");
}, []);
它会起作用我在这里更新了codesandbox供您参考:https://codesandbox.io/s/upbeat-firefly-6mqip?file=/src/App.js
在 select 下拉菜单中我添加了默认选项值“--select--”。目前它显示在 select 列表的底部。我想把它显示在列表的顶部。请帮助我如何实现这一目标。
在沙箱中我添加了代码。请找到 link:
https://codesandbox.io/s/recursing-albattani-xdeud?file=/src/App.js
分量:
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Form, Select } from "antd";
import CollegeList from "./CollegeList";
const { Option } = Select;
const App = () => {
const [collegesList, setCollegesList] = React.useState(CollegeList);
const [collegesSelectedList, setCollegesSelectedList] = React.useState([]);
useEffect(() => {
const defaultState = {
name: "--select--"
};
setCollegesList([...collegesList, defaultState]);
console.log("initial load");
}, []);
const onFinish = (values) => {
console.log("Received values of form: ", values);
};
return (
<Form name="validate_other" onFinish={onFinish}>
<Form.Item name="select" label="Select">
<Select
placeholder="Please select a country"
onChange={(college) => {
setCollegesSelectedList([
...collegesSelectedList,
collegesList[college].name
]);
}}
>
{Object.keys(collegesList).map((college) => (
<Option value={college}>{collegesList[college].name}</Option>
))}
</Select>
</Form.Item>
</Form>
);
};
export default App;
目前它显示在下拉列表的底部。
只需更新您的 setCollegesList 如下:
setCollegesList([defaultState, ...collegesList]);
console.log("initial load");
}, []);
它会起作用我在这里更新了codesandbox供您参考:https://codesandbox.io/s/upbeat-firefly-6mqip?file=/src/App.js