如何在React中添加if-else语句实现点击切换展示json-schema
解决方案
核心实现逻辑
- 首先在组件state中维护两个值:
activeSchema存储当前选中的schema名称,schemaMap存储所有schema的键值映射,避免写冗余的if-else判断 - 给每个按钮绑定点击事件,点击时更新
activeSchema的值 - 表单组件的
schema属性直接从映射表中读取当前选中的schema,实现自动切换
修改后的完整代码
import React, { Component } from 'react'; import { Row, Col, Button } from 'react-bootstrap'; // 补上缺失的Button导入 import { withTheme } from '@rjsf/core'; // 导入所有你的schema import schema1 from '../schemas/schema1.json'; import schema2 from '../schemas/schema2.json'; import schema3 from '../schemas/schema3.json'; import schema4 from '../schemas/schema4.json'; import schema5 from '../schemas/schema5.json'; import schema6 from '../schemas/schema6.json'; import { Datagrid, TextField, EditButton, DeleteButton } from 'react-admin'; // 这里引入你用的Form组件,我假设你是从@rjsf/core导入的,根据实际情况调整 import Form from '@rjsf/core'; class MyApp extends Component { constructor(props) { super(props); // 初始化state this.state = { // 默认选中第一个schema,也可以设为null默认不显示 activeSchema: 'schema1', // schema映射表,键是按钮显示的名称,值是对应的schema对象 schemaMap: { 'schema1': schema1, 'schema2': schema2, 'schema3': schema3, 'schema4': schema4, 'schema5': schema5, 'schema6': schema6 } }; this.handleSchemaChange = this.handleSchemaChange.bind(this); } // 点击按钮切换schema的方法 handleSchemaChange(schemaName) { this.setState({ activeSchema: schemaName }); } ToggleGroup() { const theme = { blue: { default: '#3f51b5', hover: '#283593', }, pink: { default: '#000000', hover: '#ad1457' } } // 从映射表取所有schema的名称,用来渲染按钮 const schemaNames = Object.keys(this.state.schemaMap); // 取当前选中的schema const currentSchema = this.state.schemaMap[this.state.activeSchema]; return (<div> <Row> {schemaNames.map(name => ( <Col key={name}> <Button active={this.state.activeSchema === name} onClick={() => this.handleSchemaChange(name)} >{name}</Button> </Col> ))} </Row> <Col> {/* 这里如果需要if-else判断的话,比如没有选中schema的时候显示提示 */} {currentSchema ? <Form schema={currentSchema} /> : <p>请先选择一个schema</p>} </Col> </div> ); } render() { return ( <> <Col> <Col> <text> List of schemas </text> </Col> </Col> <this.ToggleGroup /> </> ); } } export default MyApp;
render中使用if-else的两种方式
如果确实需要在渲染逻辑中加if-else,有两种常用写法:
- 在return前先做判断,把要渲染的内容赋值给变量,最后在jsx中引用变量:
render() { let renderContent; if (this.state.activeSchema) { renderContent = <Form schema={currentSchema} /> } else { renderContent = <p>请选择schema</p> } return <div>{renderContent}</div> }
- 在jsx中使用三元运算符,适合短的判断逻辑,就是上面代码里用到的写法。
内容的提问来源于stack exchange,提问作者Josef Carlssen
相关产品推荐
相关产品推荐

