gpt4 book ai didi

reactjs - 如何在 react 选择中设置值

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

如何在react-select中按id设置值
比如我想根据id的值来选择label值。
id = "2"结果 = "夏天"

class MyComponent extends React.Component {
constructor(props) {
super(props);

this.state = { selectedOption: "" };
}

options = [
{ id: "1", value: "Spring", label: "Spring" },
{ id: "2", value: "Summer", label: "Summer" },
{ id: "3", value: "Autumn", label: "Autumn" },
{ id: "4", value: "Winter", label: "Winter" }
];

handleChange = selectedOption => {
this.setState({ selectedOption });
};

render() {
return (
<Select
value={this.state.selectedOption}
onChange={this.handleChange}
options={this.options}
/>
);
}
}

在这里你可以看到我的 CodeSandbox .
预先感谢您的帮助和指导

最佳答案

请检查这个例子:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import Select from "react-select";

class MyComponent extends React.Component {
constructor(props) {
super(props);

this.state = {
selectedOption: ''
};
}

options = [
{ id: "1", value: "Spring", label: "Spring" },
{ id: "2", value: "Summer", label: "Summer" },
{ id: "3", value: "Autumn", label: "Autumn" },
{ id: "4", value: "Winter", label: "Winter" }
];

handleChange = selectedOption => {
this.setState({ selectedOption });
};

render() {
return (
<div>
<Select
value={this.state.selectedOption}
onChange={this.handleChange}
options={this.options}
/>
<button
onClick={() => {
let summer = this.options.find(o => o.id === "2");
this.setState({ selectedOption: summer });
}}
>
Set Summer
</button>
</div>
);
}
}

ReactDOM.render(<MyComponent />, document.getElementById("app"));

在这里你可以看到我的 CodeSandbox.

关于reactjs - 如何在 react 选择中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62054142/

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