解释如何使用react-jsonschema-form与Dash适配

解读

国内面试官问“如何适配”,核心想确认三件事:

  1. 你是否知道 Dash 的前端本质是 React,因此可以“注入”第三方 React 组件;
  2. 你是否能把社区现成的 react-jsonschema-form(RJSF)封装成 Dash 组件,而不自己重写表单逻辑;
  3. 你是否能在封装后保持 Dash 的“Python 回调”体验,让后端同事毫无感知。
    回答时务必给出“最小可运行路径”与“生产级细节”,否则会被追问性能、打包体积、SSR、许可证等问题。

知识点

  1. Dash 组件规范:组件必须暴露 id、setProps 与 children,并通过 dash-renderer 把 React props 同步到 Python 端。
  2. react-jsonschema-form 的两大产物:formData(用户填写结果)与 onSubmit/onChange 事件;需要把这两个产物通过 setProps 回传。
  3. 国内私有 npm 源与 GitLab CI:企业内网常把 @rjsf/core 同步到私有 Verdaccio,需锁定版本避免 MIT 许可证变动。
  4. 打包工具链:Dash 官方模板使用 webpack 5 + babel,需把 react 与 react-dom 标记为 externals,否则会出现多实例 Hooks 崩溃。
  5. 性能陷阱:RJSF 的 schema 较大时,每次输入都全量序列化 JSON 会导致 200 ms 以上延迟;需要 debounceSetProps 并在 React 层做 React.memo。
  6. 安全合规:金融场景下,RJSF 默认的 additionalProperties: true 会让用户注入脏字段,必须在 Python 端用 jsonschema.validate 二次校验。

答案

步骤一:初始化 Dash 组件骨架

npm install -g dash-component-boilerplate
cookiecutter https://github.com/plotly/dash-component-boilerplate
# 项目名:dash_rjsf

步骤二:安装 RJSF 并锁定版本

npm install @rjsf/core@5.12.1 @rjsf/utils @rjsf/validator-ajv8

步骤三:编写 React 层(src/lib/components/DashRjsf.react.js)

import React, {useCallback, useEffect} from 'react';
import {withTheme} from '@rjsf/core';
import {Theme as AntDTheme} from '@rjsf/antd';   // 国内团队常用 Ant Design
const Form = withTheme(AntDTheme);

export default function DashRjsf(props) {
  const {id, schema, uiSchema, formData, setProps, debounce_wait = 300} = props;

  // 防抖:避免每输入一个字符就回传
  const debounce = useCallback(
    (func, wait) => {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    }, []);

  const handleChange = useCallback(debounce((e) => {
    setProps({formData: e.formData});
  }, debounce_wait), [debounce_wait, setProps]);

  // 首次渲染时把初始数据同步回去
  useEffect(() => {
    setProps({formData});
  }, []);

  return (
    <div id={id}>
      <Form
        schema={schema}
        uiSchema={uiSchema}
        formData={formData}
        onChange={handleChange}
        onSubmit={(e) => setProps({submitted: e.formData})}
        liveValidate
        noHtml5Validate
      />
    </div>
  );
}

步骤四:声明 Dash 组件元数据(dash_rjsf/DashRjsf.py)

import json
from dash.development.base_component import Component, _explicitize_args

class DashRjsf(Component):
    @_explicitize_args
    def __init__(self, id=Component.UNDEFINED, schema=Component.REQUIRED,
                 uiSchema=Component.UNDEFINED, formData=Component.UNDEFINED,
                 debounce_wait=Component.UNDEFINED, **kwargs):
        super().__init__(**kwargs)

步骤五:Python 端使用(app.py)

from dash import Dash, html, Input, Output, callback
import dash_rjsf

app = Dash(__name__)

schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string", "title": "姓名"},
        "age": {"type": "number", "title": "年龄"}
    },
    "required": ["name"]
}

app.layout = html.Div([
    dash_rjsf.DashRjsf(id='rjsf', schema=schema, debounce_wait=500),
    html.Pre(id='output')
])

@callback(Output('output', 'children'), Input('rjsf', 'formData'))
def show(data):
    return json.dumps(data, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    app.run_server(debug=False, host='0.0.0.0', port=8050)

步骤六:生产级加固

  1. 打包体积:用 webpack-bundle-analyzer 确认 RJSF 占 350 kB,若太大,可 import {withTheme} from '@rjsf/core/dist/cjs' 关闭 Tree-shaking 未用到的主题。
  2. 服务端校验:在 onSubmit 回调里把 submitted 数据再丢给 Python 的 jsonschema.validate,防止前端被篡改。
  3. 许可证审计:RJSF 采用 Apache-2.0,需在公司 FOSS 清单登记;若使用 Ant Design 主题,需同时登记 AntD 的 MIT。
  4. 单元测试:用 dash.testing 编写 test_rjsf.py,模拟输入后断言 formData 回传正确,避免回归。

完成以上六步,即可在 Dash 中像原生组件一样使用 react-jsonschema-form,并保持国内金融、政务场景下的合规与性能要求。

拓展思考

  1. 动态 schema:当 schema 本身需要随业务变化时,可以把 schema 作为 Input 传进组件,并在 React 层用 key={JSON.stringify(schema)} 强制重新挂载表单,避免旧校验规则残留。
  2. 自定义模板:国内常见“分步表单”需求,可通过 RJSF 的 ObjectFieldTemplate 封装成 StepsForm,再把当前步骤索引通过 setProps 回传,实现 Dash 回调控制步骤条。
  3. 离线场景:在央企内网无法访问外网 CDN,需把 RJSF 的 AntD 主题与字体一并打到本地 assets 目录,并在 __init__.py 里注册 dash.register_page 的 assets_folder,确保离线可用。
  4. 微前端:若公司已有 React 微前端基座,可把 Dash 应用作为子应用,通过 single-spa 加载;此时 RJSF 组件需要暴露 bootstrap、mount、unmount 生命周期,避免与基座 React 版本冲突。