如何在REACT中使用REACT-json模式形式?

vptzau2j  于 2022-10-15  发布在  React
关注(0)|答案(2)|浏览(405)

在与json的React中,我对构建表单有问题。我已经安装了Reaction-json模式表单,但我就是不能让它工作。我在本地安装了这个包,我使用的是TypeScrip,我使用的是nx/nrwl。这就是我试过的。

import React from 'react';
import './form.scss';

const Form = JSONSchemaForm.default;
const schema = {
    type: "string"
};

/* eslint-disable-next-line */
export interface FormProps {
    json: any;
}

export const FormComponent = (props: FormProps) => {
        return (
            <>
                <Form schema={schema}/>
            </>
        );
    }
;

export default FormComponent;

问题是我从哪里获得JSONSchemaForm变量?
例如,这个小片段就像一个护身符https://codepen.io/krcaltomas99/pen/abvaJdb
谢谢你的建议!

wvt8vs2t

wvt8vs2t1#

JSONSchemaForm是使用CDN脚本导入方法时加载到Web应用程序中的导出的名称。
既然你说你安装了这个包,你可以只使用导入语法(即import Form from "@rjsf/core";),让你的绑定者来处理库依赖,而不是修改你的index.html来包含CDN脚本。

efzxgjgh

efzxgjgh2#

existing answer指出CDN脚本有一些不同的工作流程是正确的,但我感到困惑,因为import Form from "@rjsf/core";react-jsonschema-form 1.7.0上不适合我:

Module not found: Error: Can't resolve '@rjsf/core'

原来有两个不同的套餐。较旧的包(撰写本文时最后一次更新是在2019年)react-jsonschema-form适用于我,具有以下样板:

import JSONSchemaForm from "react-jsonschema-form"; // 1.7.0
import React from "react"; // 17.0.2

const formSchema = {
  type: "object",
  properties: {
    name: {
      name: "Name",
      type: "string",
      pattern: "^[a-zA-Z]+$",
      minLength: 10,
      maxLength: 50,
    },
  },
  required: ["name"],
};

const App = () => (
  <JSONSchemaForm
    onSubmit={f => console.log(f)}
    schema={formSchema}
  />
);

export default App;

下面是较新的包@rjsf/core 4.2.2的完整示例:

import Form from "@rjsf/core"; // 4.2.2
import React from "react"; // 17.0.2

const formSchema = {
  type: "object",
  properties: {
    name: {
      name: "Name",
      type: "string",
      pattern: "^[a-zA-Z]+$",
      minLength: 10,
      maxLength: 50,
    },
  },
  required: ["name"],
};

const App = () => (
  <Form
     onSubmit={f => console.log(f)}
     schema={formSchema}
  />
);

export default App;

为了完整起见,以下是CDN版本的堆栈代码片段:

const Form = JSONSchemaForm.default;
// or const {default: Form} = JSONSchemaForm;

const schema = {
  title: "Todo",
  type: "object",
  required: ["title"],
  properties: {
    title: {type: "string", title: "Title", default: "A new task"},
    done: {type: "boolean", title: "Done?", default: false}
  }
};

const log = (type) => console.log.bind(console, type);

ReactDOM.createRoot(document.querySelector("#app"))
  .render(
    <Form schema={schema}
        onChange={log("changed")}
        onSubmit={log("submitted")}
        onError={log("errors")} />
  );
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@rjsf/core@4.2.3/dist/react-jsonschema-form.js"></script>
<div id="app"></div>

相关问题