问题
I am trying to use this library "react-jsonschema-form" to create forms using react and jsonschema. I am trying to use it in my project as described in the example from the website by including the .js file via cdn. It is not working. The exported component "Form" is undefined.
I had a look at this similar question Using React component from js source maps but I could not understand the solution offered. I am supposed to alias the default export of JSONSchemaForm. But what is JSONSchemaForm? and where can I find it? Is it another library to be included?
Here is what I tried to do:
Using Require.js I have imported the cdn library:
var require = {
baseUrl: "/js/",
waitSeconds: 600,
paths: {
'react-forms': ['https://unpkg.com/react-jsonschema-form/dist/react-jsonschema-form']
},
}
Then in my code I import the library:
var rf = require('react-forms')
But now when I access Form (rf.Form), it is undefined. I had a look at the "react-jsonschema-form.js" source code. "Form" is defined no where.
From the instructions of the library page it is said:
You'll also need to alias the default export property to use the Form component:
const Form = JSONSchemaForm.default;
// or
const {default: Form} = JSONSchemaForm;
But JSONSchemaForm is also undefined.
So I don't know what I am doing wrong. How can I use "react-jsonschema-form" library by including it as a script tag?
Thank you community.
回答1:
I was able to solve this problem and I am reporting here the solution for any one facing a simlilar issue. To use react-jsonschema-form via cdn script tag (with require.js):
include this library via require.js by indicating the url path :
paths: {
'react-forms': ['https://unpkg.com/react-jsonschema-form/dist/react-jsonschema-form'] }include this polyfill library:
cdn.polyfill.io/v2/polyfill.min.js
Make sure to use the latest react version ( version v15)
In you code, require the library and alias its default export like this:
var rf = require("react-forms"); const Form = rf.default;
(This is because I am using require.js module system. For another module system, you may use JSONSchemaForm.default)
回答2:
1. Include the cdn path
<script src="https://cdn.jsdelivr.net/npm/react-jsonschema-form@1.0.3/dist/react-jsonschema-form.js"></script>
2.By using field get the access of jsonformDefaultValues;
` <script type="text/babel"
const fields = JSONSchemaForm.default
return(
<Form
schema={schema}
uiSchema={uiSchema}
field={fields}
onSubmit={onSubmit}
</Form>)
</script>`
来源:https://stackoverflow.com/questions/40312418/react-jsonschema-form-how-to-use-it-via-cdn