我尝试了以下代码,但是它设置并获取所选值的整个json。选择后如何只设置value
中的selectedOption
而不从json
中获取selectedOption
的整个state
。官方文档中给出的代码如下:
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
答案 0 :(得分:0)
您应该将handleChange
绑定到constructor
因为默认情况下,react-reselect
绑定代码行https://github.com/JedWatson/react-select/blob/master/.babelrc#L4中的所有方法
transform-class-properties
中的 .babelrc
绑定
请这样绑定: https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
此处是您问题的答案
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
constructor() {
this.handleChange = this.handleChange.bind(this)
}
handleChange = (selectedOption) => {
console.log('selectedOption', selectedOption); // log here before set state
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
答案 1 :(得分:-2)
提取所选值并传递给处理程序
onChange={(e) => this.handleChange(e.value)}
...
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={(e) => this.handleChange(e.value)}
options={options}
/>
);
}
}