gpt4 book ai didi

reactjs - 在 react-select 功能组件中设置 defaultValue

转载 作者:行者123 更新时间:2023-12-04 13:24:46 26 4
gpt4 key购买 nike

我正在使用 react-select 构建一个可重用的组件来选择美国州。
我的数据(小样本):

 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>
任何建议如何让这个工作?
Codesandbox link

最佳答案

您需要为 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>
);
}

关于reactjs - 在 react-select 功能组件中设置 defaultValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69244591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com