How can I work with just values in react-select onChange event and value prop?

陌路散爱 提交于 2019-12-06 21:07:40

AFAIK currently there's no way to make React-Select work internally with just the value. What I'm doing in my application is implementing a layer to retrieve the object going down, and extract the value going up. Something like this (this is simplified, you may need more validation or handling depending on your application):

const Select extends Component {
  handleChange(newSelected) {
    // this.props.handleChange is your own function that handle changes
    // in the upper scope and receives only the value prop of the object
    // (to store in state, call a service, etc)
    this.props.handleChange(newSelected.value);
  }

  render() {
    // Assuming you get the simple value as a prop from your store/upper 
    // scope, so we need to retrieve the option object. You can do this in 
    // getDerivedStateFromProps or wherever it suits you best
    const { options, value } = this.props;
    const selectedOption = options.find(option => option.value === value)

    <ReactSelect
      options={options}
      value={selectedOption}
      onChange={this.handleChange}
      {...props}
    />
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!