JSON Schema嵌套依赖场景下基于嵌套复选框的条件渲染实现咨询
你写的Schema语法合法但逻辑不符合JSON Schema依赖规则的生效要求,问题出在两点:
- JSON Schema的
dependencies关键字仅作用于当前Schema对应对象的同级属性,你把规则写在根Schema层级,只能监听根层的test属性,无法直接监听test下的嵌套属性enabled - 根Schema的
dependencies下test对应的规则结构不符合规范,额外加了一层enabled,JSON Schema无法识别这层的逻辑含义
以下是两种常见场景的解决方案:
场景1:勾选test.enabled后,在test对象内渲染输入框
把依赖规则直接放到test对应的对象Schema内部即可:
{ "type": "object", "properties": { "test": { "type": "object", "properties": { "enabled": { "type": "boolean", "title": "是否启用" } }, "dependencies": { "enabled": { "oneOf": [ { "properties": { "enabled": { "enum": [true] }, "lastName": { "type": "string", "title": "姓氏" } } } ] } } } } }
场景2:勾选test.enabled后,在根层级渲染输入框
跨层级的依赖更推荐用JSON Schema标准的if/then语法实现,兼容性更好:
{ "type": "object", "properties": { "test": { "type": "object", "properties": { "enabled": { "type": "boolean", "title": "是否启用" } } } }, "if": { "properties": { "test": { "properties": { "enabled": { "const": true } }, "required": ["enabled"] } } }, "then": { "properties": { "lastName": { "type": "string", "title": "姓氏" } } } }
如果你使用的是react-jsonschema-form(rjsf)框架,以上两种写法在v4及以上版本都可以正常触发条件渲染,低版本建议先升级到稳定的v4+版本。
内容的提问来源于stack exchange,提问作者InsOp
相关产品推荐
相关产品推荐

