react-jsonschema-form表单错误跟踪系统集成方案

【免费下载链接】react-jsonschema-form 【免费下载链接】react-jsonschema-form 项目地址: https://gitcode.com/gh_mirrors/rea/react-jsonschema-form

在Web应用开发中,表单错误处理是提升用户体验的关键环节。react-jsonschema-form(以下简称RJF)作为一款强大的表单生成工具,提供了完善的错误跟踪机制。本文将详细介绍如何在RJF中集成和定制错误跟踪系统,帮助开发者快速定位和解决表单验证问题。

错误跟踪核心组件

RJF的错误跟踪系统主要依赖于ErrorList组件和验证机制。ErrorList组件负责展示表单验证过程中产生的所有错误信息,其实现位于各个UI主题包中。以Material-UI主题为例,错误列表组件的路径为packages/mui/src/ErrorList/ErrorList.tsx

该组件通过errors属性接收验证错误数组,并使用Material-UI组件渲染错误列表:

<Paper elevation={2}>
  <Box mb={2} p={2}>
    <Typography variant='h6'>{translateString(TranslatableString.ErrorsLabel)}</Typography>
    <List dense={true}>
      {errors.map((error, i: number) => (
        <ListItem key={i}>
          <ListItemIcon>
            <ErrorIcon color='error' />
          </ListItemIcon>
          <ListItemText primary={error.stack} />
        </ListItem>
      ))}
    </List>
  </Box>
</Paper>

验证机制与错误生成

RJF的验证流程在packages/core/src/components/Form.tsx中实现。表单组件通过validate方法触发验证,并将结果存储在组件状态中:

validate(
  formData: T | undefined,
  schema = this.props.schema,
  altSchemaUtils?: SchemaUtilsType<T, S, F>,
  retrievedSchema?: S
): ValidationData<T> {
  const schemaUtils = altSchemaUtils ? altSchemaUtils : this.state.schemaUtils;
  const { customValidate, transformErrors, uiSchema } = this.props;
  const resolvedSchema = retrievedSchema ?? schemaUtils.retrieveSchema(schema, formData);
  return schemaUtils
    .getValidator()
    .validateFormData(formData, resolvedSchema, customValidate, transformErrors, uiSchema);
}

验证结果包含错误信息数组和错误 schema,通过onError回调函数可以获取这些信息:

it('should trigger onError call', () => {
  sinon.assert.calledWithMatch(onError.lastCall, [
    {
      message: 'is a required property',
      name: 'required',
      params: { missingProperty: 'foo' },
      property: '.foo',
      schemaPath: '#/required',
      stack: '.foo is a required property',
    },
  ]);
});

错误展示位置配置

RJF提供了灵活的错误展示位置配置,可以通过showErrorList属性控制错误列表的显示位置:

  • top:在表单顶部显示错误列表
  • bottom:在表单底部显示错误列表
  • false:不显示错误列表,仅在字段旁显示错误

配置示例:

const compInfo = createFormComponent({
  showErrorList: 'bottom',
  schema,
  formData: {
    foo: undefined,
  },
});

packages/core/src/components/Form.tsx中,通过renderErrors方法根据配置渲染错误列表:

renderErrors(registry: Registry<T, S, F>) {
  const { errors, errorSchema, schema, uiSchema } = this.state;
  const { formContext } = this.props;
  const options = getUiOptions<T, S, F>(uiSchema);
  const ErrorListTemplate = getTemplate<'ErrorListTemplate', T, S, F>('ErrorListTemplate', registry, options);

  if (errors && errors.length) {
    return (
      <ErrorListTemplate
        errors={errors}
        errorSchema={errorSchema || {}}
        schema={schema}
        uiSchema={uiSchema}
        formContext={formContext}
        registry={registry}
      />
    );
  }
  return null;
}

自定义错误跟踪实现

1. 自定义错误列表组件

通过自定义ErrorListTemplate,可以完全控制错误展示的样式和内容。首先创建自定义错误列表组件:

const CustomErrorList = ({ errors, errorSchema, schema, uiSchema, formContext }) => (
  <div className="custom-error-list">
    <h3>表单验证错误 ({errors.length})</h3>
    <ul>
      {errors.map((error, index) => (
        <li key={index} data-field={error.property}>
          <strong>{error.property}</strong>: {error.message}
        </li>
      ))}
    </ul>
  </div>
);

然后在表单中使用自定义组件:

<Form
  schema={schema}
  uiSchema={uiSchema}
  formData={formData}
  templates={{
    ErrorListTemplate: CustomErrorList
  }}
/>

2. 自定义验证逻辑

RJF支持通过customValidate属性添加自定义验证逻辑:

function customValidate(formData, errors) {
  const { pass1, pass2 } = formData;
  if (pass1 !== pass2) {
    errors.pass2.addError("Passwords don't match");
  }
  return errors;
}

const { node, onError } = createFormComponent({
  schema,
  customValidate,
  formData,
});

自定义验证可以与JSON Schema验证结合使用,提供更灵活的验证能力。

3. 实时验证配置

通过设置liveValidate属性为true,可以实现实时验证,用户输入时立即显示验证结果:

const { onChange, node } = createFormComponent({
  schema,
  customValidate,
  formData,
  liveValidate: true,
});

实时验证在packages/core/test/validate.test.js中有详细测试案例。

错误跟踪高级应用

1. 错误转换与国际化

使用transformErrors属性可以转换错误信息,实现国际化或自定义错误消息:

<Form
  schema={schema}
  formData={formData}
  transformErrors={(errors) => {
    return errors.map(error => {
      if (error.name === 'required') {
        return {
          ...error,
          message: `字段 ${error.params.missingProperty} 是必填项`
        };
      }
      return error;
    });
  }}
/>

2. 错误状态管理

表单组件的错误状态可以通过onChange回调实时获取,便于集成到全局状态管理:

<Form
  schema={schema}
  formData={formData}
  onChange={(data) => {
    // 将错误信息存储到全局状态
    dispatch({
      type: 'SET_FORM_ERRORS',
      payload: data.errors
    });
  }}
/>

3. 错误聚焦与滚动定位

设置focusOnFirstError属性为true,可以在表单提交时自动聚焦到第一个错误字段:

<Form
  schema={schema}
  formData={formData}
  focusOnFirstError={true}
/>

对于自定义滚动行为,可以结合onError回调实现:

<Form
  schema={schema}
  formData={formData}
  onError={(errors) => {
    if (errors.length > 0) {
      const firstErrorField = document.querySelector(`[name="${errors[0].property}"]`);
      if (firstErrorField) {
        firstErrorField.scrollIntoView({ behavior: 'smooth' });
        firstErrorField.focus();
      }
    }
  }}
/>

总结与最佳实践

react-jsonschema-form提供了强大的错误跟踪系统,通过合理配置和定制,可以显著提升表单用户体验。以下是一些最佳实践:

  1. 合理配置错误展示位置:根据表单长度和复杂度选择合适的错误展示位置
  2. 使用实时验证:对简单表单启用实时验证,复杂表单可在提交时验证
  3. 自定义错误信息:通过transformErrors提供清晰、友好的错误提示
  4. 结合自定义验证:JSON Schema验证与自定义验证结合,满足复杂业务需求
  5. 错误状态集中管理:将错误信息集成到全局状态,便于在应用其他部分使用

RJF的错误跟踪系统在packages/core/src/components/Form.tsx中实现核心逻辑,通过灵活配置和扩展,可以满足各种复杂场景的需求。建议开发者深入研究测试用例和源码,充分利用RJF提供的错误跟踪能力。

【免费下载链接】react-jsonschema-form 【免费下载链接】react-jsonschema-form 项目地址: https://gitcode.com/gh_mirrors/rea/react-jsonschema-form

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐