微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

基于相关记录字段的React Admin Change字段

如何解决基于相关记录字段的React Admin Change字段

比方说,我有一个名为“资产”的记录,其中有一个名为deducitble的列。资产可以有一个保险人。保险公司有一个布尔字段“ allowOtherDeductible”。

在编辑资产时,我希望能够首先检查关联的保险公司是否将allowOtherDeductible设置为true。如果是这样,我将为免赔额允许TextInput,如果为false,则为SelectInput。

我该如何实现?有条件渲染字段时,我看不到一种获取相关记录字段的方法

解决方法

我最终拉入了所有保险公司,并在加载组件时加载了资产。似乎效率不高,但我无法提出更好的方法:

export const AssetEdit = props => {
  const dataProvider = useDataProvider();
  const [insurers,setInsurers] = useState([]);
  const [asset,setAsset] = useState(null);
  const [otherDeductible,setOtherDeductible] = useState(false);

  useEffect(() => {
    dataProvider.getOne('assets',{ id: props.id })
    .then(({ data }) => {
      setAsset(data);
      return dataProvider.getList('insurers',{ pagination: { page: 1,perPage: 100 } });
    })
    .then(({ data }) => setInsurers(data))
    .catch(error => {
      console.log(error)
    })
  },[])

  useEffect(() => {
    if (asset && insurers) {
      const selectedInsurer = insurers.find(insurer => insurer.id === asset?.insurer_id);
      setOtherDeductible(selectedInsurer?.other_deductible);
    }
  },[insurers])

return (
    <Edit {...props}>
      <SimpleForm>
        {otherDeductible &&
        <NumberInput
          source={'deductible'}
          parse={val => dollarsToCents(val)}
          format={val => centsToDollars(val)}
        />
        }

        <FormDataConsumer>
          {({ formData,...rest }) => {
            if(!otherDeductible){
              return <SelectInput
                source="deductible"
                parse={val => dollarsToCents(val)}
                format={val => centsToDollars(val)}
                choices={getDeductibleChoices(formData.insured_value)}
              />
            }
          }}
        </FormDataConsumer>
      </SimpleForm>
    </Edit>
)
}
,

我会利用SimpleForm向其所有子级注入record的事实来编写自定义输入:

const DeductibleInput = ({ record }) => {
    if (!record) return null;
    const { data,loaded } = useGetOne('insurers',record.insured_id);
    if (!loaded) return null; // or a loader component
    return data.otherDeductible 
      ? <NumberInput
          source="deductible"
          parse={val => dollarsToCents(val)}
          format={val => centsToDollars(val)}
        />
      : <SelectInput
          source="deductible"
          parse={val => dollarsToCents(val)}
          format={val => centsToDollars(val)}
          choices={getDeductibleChoices(record.insured_value)}
         />
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。