首页 > 解决方案 > 在 react-select 功能组件中设置 defaultValue

问题描述

我正在使用 react-select 构建一个可重用的组件来选择美国州。我试图传入一个州值(如“OH”)来设置默认值,但似乎无法解决这个问题。

我的数据(小样本):

 const statesJson = [
  {
    "label": "Alabama",
    "value": "AL"
  },
  {
  "label": "Alaska",
  "value": "AK"
  },
  {
  "label": "American Samoa",
  "value": "AS"
  },
  {
  "label": "Arizona",
  "value": "AZ"
  },
  {
  "label": "Ohio",
  "value": "OH"
  }
]

我的组件:

import React, { Fragment, useState} from "react";
import statesJson from "./states";
import Select, { components } from "react-select";
import styled from "styled-components";
import PropTypes from "prop-types";

const StyledSelect = styled(Select)`
  font-size: 16px;
  font-weight: normal;
  color: #041e41;
  width: 250px;
`;

const propTypes = {
    id: PropTypes.string,
    onChange: PropTypes.func,
    className: PropTypes.string
};

const styles = {
    dropdownIndicator: (base: any) => ({
        ...base,
        color: "#65A100"
    }),
    menuList: (base: any) => ({
        ...base,
        height: "auto",
        border: "1px solid #0173c6",

        "::-webkit-scrollbar": {
            width: "9px"
        },
        "::-webkit-scrollbar-track": {
            background: "white"
        },
        "::-webkit-scrollbar-thumb": {
            background: "#0173C6"
        },
        "::-webkit-scrollbar-thumb:hover": {
            background: "#555"
        }
    })
}

const USStates: any[] = statesJson;

export function SelectState(props: any) {
    const [selected, setSelected] = useState();

    return (
        <StyledSelect
            {...props}
            styles={styles}
            value={selected}
            placeholder="Select a State"
            onChange={(item: any) => {
                setSelected(item);
                props.onChange(item.value);
            }}
            options={props.options.map((item: any) => ({ label: item.value + ' - ' + item.label, value: item.value }))}
        />
    );
};

export default function StateSelectDropDown(props: any) {
    return (
        <Fragment>
            <SelectState
                isSearchable
                defaultValue={props.state}
                options={USStates}
                onChange={(item: any) => {
                    alert(item);
                }}
            />
        </Fragment>
    );
}

和页面中的代码片段:

<div>
  <StateDropDown  state="OH" />
</div>

有什么建议如何让它工作吗?

代码沙盒链接

标签: reactjsreact-select

解决方案


您需要为 defaultValue 提供完整的值对象才能工作。这应该有效:

export default function StateSelectDropDown(props: any) {
  return (
    <Fragment>
      <SelectState
        isSearchable
        defaultValue={USStates.find(({ value }) => value === props.state)}
        options={USStates}
        onChange={(item: any) => {
          console.log(item);
        }}
      />
    </Fragment>
  );
}

推荐阅读