我有一个 react-select 组件,我这样定义:
<Select
id="portf"
options={opts}
onChange={value => portfolioSelector(value)}
placeholder="Select Portfolio"
/>
使用 opts = [{label: any, value:1}, {label:Two, value:2}]
。
选择时的值通过 portfolioSelector
函数存储在状态中。问题是当我选择一个值时,它没有显示在选择字段中。我的主要组成部分是这样的:
const PortfolioSelector = ({
opts,
portfolioSelector
}) => {
if (opts) {
return (
<div className="portfolio select-box">
<label htmlFor="selectBox" className="select-box__label">
Portfolio
</label>
<div className="select-box__container">
<Select
id="portf"
options={opts}
onChange={value => portfolioSelector(value)}
placeholder="Select Portfolio"
/>
</div>
<div className="separator" />
</div>
);
}
return (
<div>Loading</div>
);
};
你知道为什么吗?
最佳答案
这是我使用的替代解决方案。
演示: https://codesandbox.io/s/github/mkaya95/React-Select_Set_Value_Example
import React, { useState } from "react";
import Select from "react-select";
export default function App() {
const [selectedOption, setSelectedOption] = useState("none");
const options = [
{ value: "none", label: "Empty" },
{ value: "left", label: "Open Left" },
{ value: "right", label: "Open Right" },
{
value: "tilt,left",
label: "Tilf and Open Left"
},
{
value: "tilt,right",
label: "Tilf and Open Right"
}
];
const handleTypeSelect = e => {
setSelectedOption(e.value);
};
return (
<div>
<Select
options={options}
onChange={handleTypeSelect}
value={options.filter(function(option) {
return option.value === selectedOption;
})}
label="Single select"
/>
</div>
);
}
关于javascript - React-select 不显示字段中选择的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43250854/