从步骤 1 下拉列表中,如果用户在提交后选择一个,则将其重定向到 step2schema,如果用户选择两个,则在提交到 step3schema 后将其重定向。这是 jsfiddle(检查我的链接):
const Form = JSONSchemaForm.default;
const step1schema = {
title: "Step 1",
type: "number",
enum: [1, 2],
enumNames: ["one", "two"]
};
const step2schema = {
title: "Step 2",
type: "object",
required: ["age"],
properties: {
age: {type: "integer"}
}
};
const step3schema = {
title: "Step 3",
type: "object",
required: ["number"],
properties: {
number: {type: "integer"}
}
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {step: 1, formData: {}};
}
onSubmit = ({formData}) => {
if (this.state.step === 1) {
this.setState({
step: 2,
formData: {
...this.state.formData,
...formData
},
});
} else {
alert("You submitted " + JSON.stringify(formData, null, 2));
}
}
render() {
return (
<Form
schema={this.state.step === 1 ? step1schema : step2schema}
onSubmit={this.onSubmit}
formData={this.state.formData}/>
);
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://npmcdn.com/react-jsonschema-form@1.0.0/dist/react-jsonschema-form.js"></script>
<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>
https://jsfiddle.net/bogdanul11/sn4bnw9h/29/
这是我用于文档的库:https://github.com/mozilla-services/react-jsonschema-form
为了达到我想要的行为,我需要改变什么?
最佳答案
首先将您的状态替换为此
this.state = {step: 0, formData: {}};
然后将您的 onSubmit
逻辑替换为
onSubmit = ({formData}) => {
const submitted = formData;
this.setState({
step: submitted,
formData: {
...this.state.formData,
...formData
},
})
}
最后替换您的架构逻辑
schema={this.state.step === 0 ? step1schema : ( this.state.step === 1 ? step2schema : step3schema)}
模式选择三元运算就是我们所说的复合三元运算。如果 state.step
为 0 ,我们选择 step1schema...如果不是运行新的选择语句 ( this.state.step === 1 ? step2schema : step3schema)
;其中,如果步骤为 1,则选择 step2schema,对于其他任何情况,则选择 step3schema。
假设您有超过 3 个模式并且您想要访问它们。为此,您必须在数组中定义模式并使用索引访问它们。
schemaArray = [ {
// schema1 here
} , {
// schema2 here
} , {
// schema3 here
}, {
// schema4 here
}, {
....
}]
现在您必须使用您选择的架构
schema = { schemaArray[ this.state.step ] }
关于javascript - React json 模式形成关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47175703/