I am a complete beginner at react so a lot of simple syntax is confusing to me. I have a jsonschema form that renders perfectly fine in my create-react-app, but I don't understand how to get the data from the form when I submit it.
This is my App component (it renders I swear).
class App extends Component {
App(){
}
render() {
return (
<div className="App">
<div>
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
<div class = "json">
<Form schema={schema}
onChange={log("changed")}
onSubmit={onSubmit}
onError={log("errors")} />
</div>
</div>
);
}
}
The following is in the non JSX portion of my code.
const schema = {
type: "object",
properties: {
summary: {type: "string"},
location: {type: "string"},
description: {type: "string"},
sendNotifications: {type: "boolean", default: false},
...and so forth...
}
const onSubmit = ({formData}) => console.log("yay I'm valid!");
If I leave it as it is, when I hit submit nothing happens. If I add () braces to the onSubmit call in the render method, it yields the error "cannot read property formData of undefined". I know virtually nothing about props, or how props are supposed to be defined. I would appreciate any help! Thank you!
答案 0 :(得分:0)
使用class
组件时,您需要使用this
关键字onSubmit={this.onSubmit}
来引用处理程序。
作为旁注,您应该改变构造函数的编写方式
查看代码的工作示例:
const Form = JSONSchemaForm.default;
class App extends React.Component {
constructor(props){
super(props);
}
schema = {
type: "object",
properties: {
summary: {type: "string"},
location: {type: "string"},
description: {type: "string"},
sendNotifications: {type: "boolean", default: false},
}
}
onSubmit = ({formData}) => console.log("yay I'm valid!");
render() {
return (
<div className="App">
<div>
<div className="App-header">
<img src="" className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
</div>
<div class = "json">
<Form schema={this.schema}
onSubmit={this.onSubmit}
/>
</div>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-jsonschema-form/dist/react-jsonschema-form.js"></script>
<div id="root"></div>