【问题标题】:React-select save props反应选择保存道具
【发布时间】:2018-10-08 17:43:29
【问题描述】:

我正在使用 react-select 在我的 UI 上启用多项选择。但是,我需要从这个 react-select 中获取道具,因为我会将选择值发送到后端。我想知道。如何将状态值保存在数组中。我做了一个console.log,我得到的值是

0: {value: "vanilla", label: "Vanilla"}
1: {value: "strawberry", label: "Strawberry"}
2: {value: "chocolate", label: "Chocolate"}.

但是,我只想要值标签,因为我会将这个确切的值(例如 vanilla)发送到后端。有什么建议么。非常感谢。 react-select 的 github link 是:

    import React, { Component } from "react";
    import { connect } from "react-redux";
    import PropTypes from "prop-types";
    import checkboxes from "./checkboxes";
    import Checkbox from "./Checkbox";
    import Select from "react-select";
    const options = [
      { value: "chocolate", label: "Chocolate" },
      { value: "strawberry", label: "Strawberry" },
      { value: "vanilla", label: "Vanilla" }
    ];

    class CreatePreferences extends Component {
    state = {
    selectedOption: null
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        isMulti
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}
CreatePreferences.propTypes = {
  profile: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  profile: state.profile
});

export default connect(mapStateToProps)(CreatePreferences);

【问题讨论】:

    标签: javascript reactjs forms


    【解决方案1】:

    要做的事情很少:您需要一个构造函数来定义一个状态,并且您需要使用选定的值更新这个状态。

    Online Sandbox Demo

    用构造函数定义你的状态,如...

      constructor(props) {
        super();
        this.state = {
          selectedOptions: [],
        };
      }
    

    并像这样定义您的事件处理程序。 (您要求保存“标签”,通常显示的是“标签”,保存的是“值”,但无论如何,按要求...)...

      handleChange = selectedOption => {
        const state = this.state;
        state.selectedOptions = [];
        selectedOption.forEach((option) => {
          state.selectedOptions.push(option.label);
        });
        this.setState(state);
        console.log(`Options selected:`, JSON.stringify(state.selectedOptions, null, 4));
      };
    

    在这里,你会看到这样的输出......

    Options selected: [
        "Chocolate"
    ]
    Options selected: [
        "Chocolate",
        "Strawberry"
    ]
    

    通常,要让 render() 函数和状态一起工作,还有很多事情要做,这在 ReactJS 中总是如此。

    但您似乎正在使用React-Select,它似乎会自动处理其中的一些:React-Select Github Page

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      相关资源
      最近更新 更多