如何在react-admin中为React RRule Generator设置默认值?

问题描述

我正在使用 react-admin react-rrule-generator https://github.com/Fafruch/react-rrule-generator)。使用rrule小部件时,创建/添加记录工作正常。但是,每当我尝试编辑记录时,小部件都应根据记录的值自动填充其值。但是该值始终是窗口小部件本身提供的认值。这是我的代码

main_file.jsx

export const JobCreate = (props) => {
  return (
    <Create {...props}>
      <SimpleForm>
        <CustomrRuleInput name="recurrency" label="Recurrency" />
      </SimpleForm>
    </Create>
  )
}

recurrency_field.jsx

export const CustomrRuleInput = (props) => {
  const {
    input: { onChange },Meta: { touched,error },} = useInput(props)

  return (
    <Labeled label={props.label}>
      <RRuleGenerator
        onChange={onChange}
        name={props.name}
      />
    </Labeled>
  )
}

如果我在value={props.record.recurrency}组件中添加RRuleGenerator,我将无法更改值,因为即使尝试更改它们,我也会固定/硬编码恒定的值。如果这个小部件有一个名为defaultValue的道具,那就可以了! 我该如何实现?

解决方法

如果仔细检查文档的Inputs/Writing your own input部分,您会注意到使用useFielduseInput钩子的自定义输入组件仍会收到source道具,该道具将通过输入作为挂钩参数的一部分。

尝试一下:

在main_file.jsx内部

<CustomRRuleInput source="recurrency" label="Recurrency" />

recurrency_field.jsx内部

const {
    input: { name,onChange },meta: { touched,error },} = useInput(props)

  return (
    <Labeled label={props.label}>
      <RRuleGenerator
        onChange={onChange}
        name={name}
      />
    </Labeled>
  )
  
,

没关系,我做到了!我可以用它来创建和更新记录。我还使用rrule库将rrule转换为人类可读的文本,该文本显示在RRule小部件下方的TextInput字段中。当您在RRule小部件中更改数据时,文本会动态更改。

recurrency_field.jsx

import RRuleGenerator from "react-rrule-generator"
import React,{ useState } from "react"
import { useInput,Labeled,TextInput } from "react-admin"
import { rrulestr } from "rrule"


export const CustomRRuleInput = (props) => {
  const record = props.record
  const {
    input: { onChange },} = useInput(props)

  const [state,setState] = useState(record[props.name])

  return (
    <>
      <Labeled label={props.label}>
        <RRuleGenerator
          onChange={(val) => {
            setState(val)
            onChange(val)
          }}
          value={state}
          name={props.name}
        />
      </Labeled>

      <TextInput
        fullWidth
        disabled
        label={"RRule Text"}
        value={state ? rrulestr(state).toText() : ""}
      />
    </>
  )
}

main_file.jsx

<CustomRRuleInput name="recurrency" label="Recurrency(r rule)" />