react-native - FormProvider 内的 useFormContext 为 null

标签 react-native expo react-hook-form

我正在使用react-hook-form来处理表单,并且遇到了一个仅发生在iOS上的错误(在android上工作正常),它告诉我useFormContext为空。该代码包含三个组件,因此我在 expo 上编写了示例,您可以找到 here ,正如您所看到的,我正在使用 FormProvider,因此上下文应该发送给子级。有人知道如何解决这个问题吗?

Cannot read properties of null (reading 'control')
TypeError: Cannot read properties of null (reading 'control')
    at FormSelect 
<FormProvider {...methods}>
          <Dialog
            title={'issue-card'}
            body={
              <FormSelect
                name="card"
                label={'card-number'}
                options={cards}
              />
            }
            ...
          />
        </FormProvider>
export const FormSelect = ({
  label,
  options,
  name,
}) => {
  const { control } = useFormContext();
  const {
    field: { value, onChange },
    fieldState: { error },
  } = useController({ name, control });

  return (
    <FormControl>
        <Select
          onValueChange={onChange}
          selectedValue={value}
          variant="filled"
          _selectedItem={{ background: 'primary.black' }}
        >
          {options.map((option) => (
            <Select.Item
              key={`temporary--${value}`}
              label={option.number}
              value={option.number}
            />
          ))}
        </Select>
    </FormControl>
  );
};

最佳答案

我在这里添加我的答案,因为这正是我刚刚遇到的问题,它可能对其他人有帮助。对于我们来说,问题在于 react-hook-form 版本之间不兼容。 :

  1. 我们在可重复使用的包中开发了一些组件,使用 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e09285818394cd888f8f8bcd868f928da0d7ced3d6ced0" rel="noreferrer noopener nofollow">[email protected]</a>
  2. 我们尝试在使用 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6d4c3c7c5d28bcec9c9cd8bc0c9d4cbe69188959f8896" rel="noreferrer noopener nofollow">[email protected]</a> 的消费项目中使用这些组件(通过 NPM 包) .

调整 react-hook-form 的版本让我们的问题迎刃而解。


但在您的特定情况下,看起来是因为 Dialog 的方式控制正在呈现其子项;如果你移动FormProvider在主体内部,然后控件将按照您的预期呈现:

<Dialog
  title={'issue-card'}
  body={
    <FormProvider {...methods}>
      <FormSelect
        name="card"
        label={'card-number'}
        options={cards}
      />
    </FormProvider>
  }
/>

关于react-native - FormProvider 内的 useFormContext 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73153264/

相关文章:

react-native - 如何在 React-Native (Expo) 中对图像数据进行哈希处理?

react 原生,开 Jest ,ts-jest : ReferenceError: React is not defined

reactjs - 使用 laravel api 从 React 上传图像

reactjs - useEffect 未在 react Hook 表单更改时触发

node.js - 无法开始一个新的世博项目 |不再支持 Node.js 版本 14.0.0

react-native - 在 i18next 中遍历数组

react-native - 错误 : Naming collision detected

css - React Native - 在 WebView 中导入 css/js

reactjs - 当搜索或过滤器值更改时,如何从 Material UI 的数据网格中保持选择我的行

reactjs - React Native 跨平台代码库