如何在React-Select的状态下设置和获取仅值字符串

时间:2018-11-23 10:00:10

标签: reactjs react-select

我尝试了以下代码,但是它设置并获取所选值的整个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}
      />
    );
  }
}

2 个答案:

答案 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}
          />
        );
      }
    }