我正在使用 react-select 在我的 UI 上启用多项选择。但是,我需要从这个 react-select 中获取 Prop ,因为我会将选择值发送到后端。我想知道。如何将状态值保存在数组中。我做了一个 console.log,我得到的值是
0: {value: "vanilla", label: "Vanilla"}
1: {value: "strawberry", label: "Strawberry"}
2: {value: "chocolate", label: "Chocolate"}.
但是我只喜欢值标签,因为我会将这个确切的值(例如 vanilla)发送到后端。有什么建议。多谢。 github link对于 react 选择是:
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);
最佳答案
有几件事要做:您需要一个构造函数来定义一个状态,并且您需要使用选定的值更新该状态。
使用构造函数定义您的状态,如...
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
关于javascript - react 选择保存 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52707541/