首页 > 解决方案 > 如何使用 Typescript 对 React 上的组合框项目进行排序?

问题描述

我有一个项目,在项目中有一年的组合框。我将年份排序(asc to desc 或 desc to asc)。

在此处输入图像描述

我有一个表单 utils,我在组件中调用了 utils。

标签: reactjstypescriptreact-native

解决方案


试试这个方法

import React, { Component } from "react";
import Select from "react-select";

function compare(a, b) {
  return a.label > b.label ? 1 : b.label > a.label ? -1 : 0;
}

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      options: [
        {
          label: 1940,
          value: 1
        },
        {
          label: 1945,
          value: 2
        },
        {
          label: 1942,
          value: 3
        },
        {
          label: 1941,
          value: 4
        },
        {
          label: 1946,
          value: 5
        }
      ]
    };
  }

  render() {
    return (
      <Select
        //isMulti
        hideSelectedOptions={false}
        options={this.state.options.sort(compare)}
      />
    );
  }
}

这是Snack.io 上的一个示例


推荐阅读