【问题标题】:always display select option on top of select dropdown list in react js antd始终在反应 js antd 中的选择下拉列表顶部显示选择选项
【发布时间】:2021-08-27 07:57:37
【问题描述】:

在选择下拉菜单中,我添加了默认选项值“--select--”。目前它显示在选择列表的底部。我想将它显示在列表的顶部。请帮助我如何实现这一目标。

在沙盒中我添加了代码。请找到链接:

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;

目前它显示在下拉列表的底部。

【问题讨论】:

    标签: javascript reactjs antd


    【解决方案1】:

    只需更新您的 setCollegesList 如下:

        setCollegesList([defaultState, ...collegesList]);
           console.log("initial load");
      }, []);
    

    它会起作用我在这里更新了代码框供您参考:https://codesandbox.io/s/upbeat-firefly-6mqip?file=/src/App.js

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 1970-01-01
      • 2022-10-25
      • 2015-02-18
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多