【发布时间】:2019-05-28 18:15:36
【问题描述】:
我的自定义组件应该将数据传递给父级,即 react-admin <Create>
我已经遇到了一些问题,发现我不能简单地将状态从孩子设置为父母。
问题是这个组件应该像默认的 react-admin 组件(例如 )一样工作。这意味着当我提交表单时,它会从该组件获取数据。
我已经试过addField()
这是我的自定义组件(子):
import React from "react";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";
import { fetchUtils } from 'react-admin';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import { DataService } from '../routes/api';
import PropTypes from 'prop-types';
import { resources as rsrc } from '../resources';
const divStyle = {
marginTop: '16px',
marginBottom: '8px',
};
const inputStyle = {
width: '256px',
}
export default class MultipleSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
selectOptions: [],
selectedValues: [],
selectedValue: null,
};
}
getRoles() {
// get data from api
}
getAllOptions() {
// get some additional data from API
}
createRelationRecord(id) {
// create relation record (for ex. User's Role)
}
deleteRelationRecord(id) {
// delete relation record
}
componentDidMount() {
this.getRoles();
this.getAllOptions();
}
renderSelectOptions = () => {
return this.state.selectOptions.map((dt, i) => (
<MenuItem key={dt.id} value={dt.id}>
{dt.value}
</MenuItem>
));
};
handleChange = event => {
this.setState({ selectedValue: event.target.value });
// If record doesn't exist
if (this.state.selectedValue != event.nativeEvent.target.dataset.value) {
this.createRelationRecord(event.nativeEvent.target.dataset.value);
}
if (this.state.selectedValues.includes(Number(event.nativeEvent.target.dataset.value))) {
this.deleteRelationRecord(event.nativeEvent.target.dataset.value);
} else {
this.createRelationRecord(event.nativeEvent.target.dataset.value);
}
};
selectboxType() {
if (this.props.multiple) {
return true;
}
return false;
}
getSelected() {
if (this.selectboxType()) {
return this.state.selectedValues;
}
return this.state.selectedValue;
}
render() {
return (
<div style={divStyle}>
<FormControl>
<InputLabel htmlFor={this.props.label}>{this.props.label}</InputLabel>
<Select
multiple={this.selectboxType()}
style={inputStyle}
value={this.getSelected()}
onChange={this.handleChange}
>
{this.renderSelectOptions()}
</Select>
</FormControl>
</div>
);
}
}
父级(创建表单):
export const ServerCreate = props => (
<Create {...props}>
<SimpleForm>
<TextInput source="Name" validate={required()} />
<ReferrenceSelectBox label="ServerType" multiple={false} source="ServerTypeId" reference="ServerType"></ReferrenceSelectBox>
<TextInput source="Barcode" validate={required()} />
</SimpleForm>
</Create>
);
配合handleChange实现数据更新。现在我需要在 Create 表单中保存选择的数据,但是 handleChange 对我没有帮助,因为对象还没有创建,我无法设置不存在记录的属性。
所以我的问题是如何将值/值从我的组件传递给 Create?如何设置父母的状态?
【问题讨论】:
标签: reactjs react-admin