当我使用 React 单击按钮时,如何从 select 中选择一个选项?
How can I do to choose an option from a select when I click on a button using React?
当我使用 React
单击“Apple”按钮时,我想从 select 中选择选项“Apple”
import React from "react";
import { render } from "react-dom";
import ReactDOM from "react-dom";
import Select from "react-select";
import "react-select/dist/react-select.css";
class ReactSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
itemtitle: "",
multi: true,
multiValue: [],
options: [
{ value: "Color", label: "Yellow" },
{ value: "Fruit", label: "Apple" },
{ value: "Tool", label: "Spanner" }
]
};
}
onTitleChange(e, value) {
this.setState({ [e.target.name]: e.target.value });
this.setState({ multiValue: e.target.value });
}
handleOnChange(value) {
this.setState({ multiValue: value });
}
render() {
return (
<div>
<Select.Creatable
multi={this.state.multi}
options={this.state.options}
onChange={this.handleOnChange.bind(this)}
value={this.state.multiValue}
showNewOptionAtTop={false}
/>
<button>Apple</button>
</div>
);
}
}
ReactDOM.render(<ReactSelect />, document.body);
我的项目的完整代码在那里:
我该怎么做?非常感谢!
您可以在单击类似这样的按钮时更新 select
字段值。
handleOnClick = () => {
this.setState({ multiValue: [{ value: "Fruit", label: "Apple" }] });
};
render() {
return (
<div>
<Select.Creatable
multi={this.state.multi}
options={this.state.options}
onChange={this.handleOnChange.bind(this)}
value={this.state.multiValue}
showNewOptionAtTop={false}
/>
<button
onClick={() => {
this.handleOnClick();
}}
>
Apples
</button>
</div>
);
}
还附加了一个沙盒link。
当我使用 React
单击“Apple”按钮时,我想从 select 中选择选项“Apple”import React from "react";
import { render } from "react-dom";
import ReactDOM from "react-dom";
import Select from "react-select";
import "react-select/dist/react-select.css";
class ReactSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
itemtitle: "",
multi: true,
multiValue: [],
options: [
{ value: "Color", label: "Yellow" },
{ value: "Fruit", label: "Apple" },
{ value: "Tool", label: "Spanner" }
]
};
}
onTitleChange(e, value) {
this.setState({ [e.target.name]: e.target.value });
this.setState({ multiValue: e.target.value });
}
handleOnChange(value) {
this.setState({ multiValue: value });
}
render() {
return (
<div>
<Select.Creatable
multi={this.state.multi}
options={this.state.options}
onChange={this.handleOnChange.bind(this)}
value={this.state.multiValue}
showNewOptionAtTop={false}
/>
<button>Apple</button>
</div>
);
}
}
ReactDOM.render(<ReactSelect />, document.body);
我的项目的完整代码在那里:
我该怎么做?非常感谢!
您可以在单击类似这样的按钮时更新 select
字段值。
handleOnClick = () => {
this.setState({ multiValue: [{ value: "Fruit", label: "Apple" }] });
};
render() {
return (
<div>
<Select.Creatable
multi={this.state.multi}
options={this.state.options}
onChange={this.handleOnChange.bind(this)}
value={this.state.multiValue}
showNewOptionAtTop={false}
/>
<button
onClick={() => {
this.handleOnClick();
}}
>
Apples
</button>
</div>
);
}
还附加了一个沙盒link。