问题描述
我们可以在 SelectInput/TextField 改变时触发吗?例如,如果我们使用如下源属性为 SelectInput 字段设置值:
<SelectInput source='domain' onChange={() => {
//... fetch geo list
//... then set geo value
}}/>
然后以相同的形式,我想根据第一个选择输入值更新第二个选择输入字段,例如:
<SelectInput source='geo' .../>
但是如果我动态更新“域”的源值,那么它不会在更改时触发。有什么办法可以做到这一点。
解决方法
你必须反过来做:不是应该通知geo的域,而是应该对域更改做出反应的geo。这就是 React 的方式!
react-admin 文档(https://marmelab.com/react-admin/Inputs.html#linking-two-inputs)解释说你需要使用 react-final-form 的 useFormState 钩子来获取当前的表单状态:
import * as React from 'react';
import { Edit,SimpleForm,SelectInput } from 'react-admin';
import { useFormState } from 'react-final-form';
const countries = ['USA','UK','France'];
const cities = {
USA: ['New York','Los Angeles','Chicago','Houston','Phoenix'],UK: ['London','Birmingham','Glasgow','Liverpool','Bristol'],France: ['Paris','Marseille','Lyon','Toulouse','Nice'],};
const toChoices = items => items.map(item => ({ id: item,name: item }));
const CityInput = props => {
const { values } = useFormState();
return (
<SelectInput
choices={values.country ? toChoices(cities[values.country]) : []}
{...props}
/>
);
};
const OrderEdit = props => (
<Edit {...props}>
<SimpleForm>
<SelectInput source="country" choices={toChoices(countries)} />
<CityInput source="cities" />
</SimpleForm>
</Edit>
);
export default OrderEdit;