我正在尝试编写一个示例,其中显示了两个下拉列表:一个用于国家,另一个用于相关的州/省。当您在第一个下拉列表中选择一个国家/地区时,第二个下拉列表中的值应更新为仅显示所选国家/地区的省/州。这通常是使用某种Ajax调用来完成的,但在这种情况下,要求完全使用react-jsonschema-form来尝试它。这真的是可能的吗?我见过几个使用依赖/引用的例子,但没有一个能解决这个特定的场景。
到目前为止,我想出了这个:https://codesandbox.io/s/fervent-cherry-lokjk?file=/src/App.js
{
"definitions": {
"Countries": {
"title": "Country",
"type": "object",
"properties": {
"country": {
"type": "string",
"enum": [
"CANADA",
"USA",
"MEXICO"
]
}
},
"dependencies": {
"country": {
"oneOf": [
{
"properties": {
"country": {
"enum": [
"CANADA"
]
},
"province": {
"type": "string",
"title": "Province",
"enum": [
"AB",
"BC",
"MB"
]
}
}
},
{
"properties": {
"country": {
"enum": [
"USA"
]
},
"province": {
"type": "string",
"title": "State",
"enum": [
"AL",
"AK",
"AR"
]
}
}
},
{
"properties": {
"country": {
"enum": [
"MEXICO"
]
},
"province": {
"type": "string",
"title": "State",
"enum": [
"AGS",
"BC",
"BCS"
]
}
}
}
]
}
}
}
},
"title": "Demo for countries",
"type": "object",
"properties": {
"currentCountry": {
"$ref": "#/definitions/Countries",
"title": "Select country / province / state"
}
}
}这基本上可以呈现一个国家下拉列表和一个州/省下拉列表。选择国家/地区时,相应的州/省下拉列表将使用新的枚举值集正确更新。
但是,使用这种方法时,表单将提交一个名为"currentCountry“的字段,其中包含两个属性:国家和省份
currentCountry: { country: "USA" , province: "AL" }当然,我们的想法是将“国家”和“省份”作为两个不同的表单字段提交,而不需要包装。
那么,有人知道如何实现这个典型用例吗?有没有使用JSON模式的最好方法?
也许需要编写一个自定义的小部件?(如果可能的话,我想避免这种情况)
提前感谢!
发布于 2021-01-08 10:29:35
在玩了一段时间后,我似乎找到了解决方案。一个正确的模式恰好完成了所需的工作:
{
title: "Demo for countries",
type: "object",
properties: {
country: {
type: "string",
title: "Country",
enum: ["CANADA", "USA", "MEXICO"]
}
},
dependencies: {
country: {
oneOf: [
{
properties: {
country: {
enum: ["CANADA"]
},
province: {
type: "string",
title: "Province",
enum: ["ALBERTA", "BRITISH COLUMBIA", "MANITOBA"]
}
}
},
{
properties: {
country: {
enum: ["USA"]
},
province: {
type: "string",
title: "State",
enum: ["ALABAMA", "OREGON", "ARKANSAS"]
}
}
},
{
properties: {
country: {
enum: ["MEXICO"]
},
province: {
type: "string",
title: "State",
enum: ["JALISCO", "BAJA CALIFORNIA", "CHIAPAS"]
}
}
}
]
}
}
}上面的codesandbox示例已经更新,以反映这一变化。很高兴知道这个场景可以用JSON模式实现!
https://stackoverflow.com/questions/65597922
复制相似问题