【发布时间】:2018-06-08 12:47:13
【问题描述】:
react-select 中的 Select 组件在 label 和 value 值中保持状态。迄今为止我看到的关于将此组件集成到 redux-form 表单的建议,建议用从父 redux-form 组件隐式传递的行为覆盖默认的 react-select onChange 和 onBlur 行为。比如……
<Field component{SelectWrapper} />
class SelectWrapper extends React.Component {
onChange = event => {
if (this.props.input.onChange && event != null) {
this.props.input.onChange(event.value);
} else {
this.props.input.onChange(null);
}
}
render() {
<AsyncCreatableSelect
{...this.props}
onChange={this.onChange}
onBlur={() => this.props.input.onBlur(this.props.input.value)}
/>
}
}
我想使用文档的_id 作为value 和name 属性作为label,从MongoDB 存储中填充<Select /> 组件。然后在选择另一个选项时,我想在选择框中看到name,同时将id作为值。这样用户就可以从有意义的项目中进行选择,而我可以在提交表单并将其推回数据存储时得到一些保证。有没有好的或正确的方法来做到这一点?
到目前为止我的代码...
// CustomerSelect.js
import React from "react";
import { Field } from "redux-form";
import Grid from "material-ui/Grid";
import renderAsyncCreatableSelect from "../redux-form-connectors/renderAsyncCreatableSelect";
const CustomerSelect = ({ customers, selectedCustomer }) => {
// customers: [{name: "Alice", _id: "$7637221n...}, ...]
const options = customers.map(customer => ({
label: customer,
value: customer
}));
return (
<Grid item>
<Field
name="customer"
component={renderAsyncCreatableSelect}
label="Customer"
selectedValue={selectedCustomer}
/>
</Grid>
);
};
// renderAsyncCreatableSelect.js
import React, { Component } from "react";
import axios from "axios";
import AsyncCreatableSelect from "react-select/lib/AsyncCreatable";
const getOptions = () => {
return axios
.get("/api/customers") // [{_id: "", name: "", user: ""... }, ...]
.then(res => res.data.map(el => ({ label: el.name, value: el._id })));
};
export default class renderAsyncCreatableSelect extends Component {
onChange = (event) => {
if (this.props.input.onChange && event != null) {
this.props.input.onChange(event.value);
} else {
this.props.input.onChange(null);
}
};
render() {
const { input, selectedValue } = this.props;
return (
<AsyncCreatableSelect
cacheOptions
defaultOptions
placeholder={"Customer..."}
loadOptions={getOptions}
value={input.value ? input.value : selectedValue.label}
onBlur={() => input.onBlur(input.value)}
onChange={this.onChange}
/>
);
}
}
【问题讨论】:
标签: javascript reactjs redux-form react-select