我有一个创建组件,我希望其中一个输入来自列表。我目前拥有的代码是:
export const ContestCalendarCreate = (props) => {
const createControllerHook = useCreateController(props)
const [selectedContest, setSelectedContest] = useState<any>()
const {
record, // empty object, unless some values were passed in the location state to prefill the form
} = createControllerHook
if (selectedContest) {
record.selectedContest = selectedContest
}
const selectContest = (rowRecord) => {
record.selectedContest = rowRecord
setSelectedContest(() => rowRecord)
}
const transformData = (data) => {
data.startTimestamp = moment(data.startTimestamp).unix() * 1000
data.opensAt = moment(data.opensAt).unix() * 1000
data.start_timestamp = data.startTimestamp
data.opens_at_timestamp = data.opensAt
data.id = data.selectedContest.id
data.contest_title = data.selectedContest.contest_title
return data
}
return (
<Create {...props} transform={data => transformData(data)} >
<SimpleForm>
<DateTimeInput source="startTimestamp" disabled label="Starts At" validate={[required()]} />
<DateTimeInput source="opensAt" label="Opens At" validate={[required()]}/>
{selectedContest ?
<TextField record={record} source="selectedContest.contest_title" label="Contest" validate={[required()]}/>
:
<ReferenceManyField label="Select A Contest" reference="admin/contest" allowEmpty filter={{approved: true, states: [ContestState.unpublished]}}>
<List filters={<ContestFilter />} bulkActionButtons={false} exporter={false} sort={{ field: 'contest_title', order: 'DESC' }} >
<Datagrid rowClick={(id, path, rowRecord) => selectContest(rowRecord)}>
<TextField source="contest_title" />
<TextField source="contest_description" />
<TextField source="quiz_title" />
<TextField source="quiz_description" />
<TextField source="topics" />
</Datagrid>
</List>
</ReferenceManyField>
}
{selectedContest && <Button variant="contained" color="default" disableElevation onClick={() => selectContest(null)}>Select Another Contest</Button>}
</SimpleForm>
</Create>
)
}
selectContest功能类作品;然而,当它执行时,它会将其他表单输入重置为默认值。
有没有其他方法可以让我更改从useCreateController挂钩获得的记录?
如果我答对了你的问题,你需要在Datagrid
的行点击事件上更新当前表单中的"selectedContest"
字段。您可以使用react-final-form
挂钩useForm
和可用的更改方法,而不是覆盖记录:
const form = useForm();
// rowClick function
(id, path, rowRecord) => form.change('selectedContest', rowRecord)
在链接两个输入部分的文档中对此进行了解释:React Admin docs