我正在使用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>
有什么建议可以让它正常工作吗?