在 reux 形式状态下维护来自 react-select 组件的值和标签



一个选择组件在 react-select 中保持labelvalue值的状态。到目前为止,我看到的关于将此组件集成到 redux 表单表单中的建议建议覆盖默认的 react-selectonChange,并使用从父 redux-form 组件隐式传递的行为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作为valuename属性作为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}
/>
);
}
}

您的 onchange 函数必须看起来像

onChange = (event) => {
if (this.props.input.onChange && event.target.value != null) {
this.props.input.onChange(target.value);
} else {
this.props.input.onChange(null);
}
};

或者如果您正在使用来自字段的 redux

onChange = (event, value) => {
if (this.props.input.onChange && value != null) {
this.props.input.onChange(value);
} else {
this.props.input.onChange(null);
}
};

最新更新