react动态生成input、select标签以及思路总结

简介: 本文介绍了在React中动态生成input和select标签的方法,包括准备数据结构、在组件挂载时动态添加状态、页面渲染以及输入处理,最后总结了实现思路。

见贤思齐焉,见不贤内自省

首先我们需要有一个数据结构,首先需要是一个数组,当然字段都可以自己定义,我这里没按照规范起名。
核心在于将数据整理好,字段梳理清楚,将state中用到的字段动态插入,提醒必填项也要动态遍历。
比如:

   let stateOptions = [{
   
                value: 'name',
                title: '允许传送',
                type: 'inp',
                isrequird: true
            }, {
   
                value: 'age',
                title: '允许请求',
                type: 'sel',
                isrequird: false
            }, {
   
                value: 'runing',
                title: '允许递归',
                type: 'inp',
                isrequird: true
            }]

value标识当前字段的key
title标识当前input或者select前面的名称
type标识是input还是select
isrequird标识当前是否是必填

这里只写这几项,这是我在写项目之前的一个小样。所以并没有考虑的很全面。

我们需要在页面挂载的时候,将变量动态的添加到状态机中:

 componentDidMount() {
   
        setTimeout(() => {
   
            let stateOptions = [{
   
                value: 'name',
                title: '允许传送',
                type: 'inp',
                isrequird: true
            }, {
   
                value: 'age',
                title: '允许请求',
                type: 'sel',
                isrequird: false
            }, {
   
                value: 'runing',
                title: '允许递归',
                type: 'inp',
                isrequird: true
            }]
            //创建一个临时对象 添加属性方便
            let newObkj = {
   }
            //初始化在view层需要用到的变量 放置state中
            stateOptions.map(i => {
   
                // 到时候换成字段标识
                if (i.value === 'age') {
   
                    newObkj[i.value] = []
                } else {
   
                    newObkj[i.value] = ''
                }
            })
            //使用解构赋值的形式直接将生成好的变量对象放置state中
            this.setState({
   
                // 解构到state中
                ...newObkj,
                myOptionList: stateOptions
            })
        })

    }

页面使用:

    render() {
   
        let {
    myOptionList, } = this.state
        // 随机生成options 数组
        const children = [];
        for (let i = 10; i < 36; i++) {
   
            children.push({
    title: `${
     i.toString(36) + i}`, key: `${
     i.toString(36) + i}` });
        }
        // 必填标识  * 
        let isrequird = <a href="#!" style={
   {
    color: '#ff7875', fontSize: '12px', marginTop: '8px', marginLeft: '8px' }}>*</a>
        return (
            <div className="context" >
                <div className="search"  >
                    <div className="search-input">
                        <p className="search-input-title">{
   'XX设置'}</p>
                        <div className="search-input-row" style={
   {
    marginTop: '20px' }} style={
   {
    flexDirection: "column" }}>
                            <span style={
   {
    marginRight: '6%' }}></span>
                            <div style={
   {
    textAlign: 'right', whiteSpace: 'nowrap', display: 'flex', flexDirection: "column", justifyContent: 'space-between' }}>
                                {
   
                                    myOptionList.map((item, index) => {
   
                                        return (
                                            item.type === 'inp' ?
                                                <div key={
   index} style={
   {
    display: 'flex', marginBottom: '10px' }}>
                                                    <Input value={
   this.state[`${
     item.value}`]} title={
   `${
     item.title}`} onChange={
   (e) => this.inputName(`${
     item.value}`, e.target.value)} />
                                                    {
   item.isrequird ? isrequird : ''}
                                                </div>
                                                :
                                                item.type === 'sel' ?
                                                    <div key={
   index} className="search-input-row-element" style={
   {
    marginBottom: '10px', display: 'flex', marginLeft: '0px' }}>
                                                        <Select
                                                            title={
   `${
     item.title}:`}
                                                            showArrow={
   true}
                                                            mode="tags"
                                                            style={
   {
   }}
                                                            value={
   this.state[`${
     item.value}`]}
                                                            onChange={
   (e) => {
    this.inputName(`${
     item.value}`, e) }}
                                                            tokenSeparators={
   [',']}
                                                            options={
   children}
                                                            keyField="key"
                                                            valueField="key"
                                                            titleField="title"
                                                            dropdownMatchSelectWidth={
   true}
                                                        ></Select>
                                                        {
   item.isrequird ? isrequird : ''}
                                                    </div>
                                                    : ''
                                        )
                                    })
                                }
                            </div>
                        </div >
                    </div>
                </div>
                <div className="device_search" style={
   {
    marginLeft: "0px", marginBottom: '20px', marginTop: '20px', textAlign: "center" }}>
                    <Button Type="noIcon" title="测试按钮" onClick={
   () => this.bottomBtnClick('1')}></Button>
                    <span style={
   {
    marginRight: '20px' }}></span>
                    <Button Type="noIcon" color="#E6A23C" title="返回" onClick={
   () => this.bottomBtnClick('2')}></Button>
                </div>
            </div>
        )
    }

上方使用三木运算判断标识显示input组件还是select组件,是否显示必填的标识。
动态生成了select中的options。
input和select输入获取值放置统一方法中:

    // 输入框 输入
    inputName = (type, e) => {
   
        let tempData = {
   }
        if (e.target) {
   
            tempData[type] = e.target.value
        } else {
   
            tempData[type] = e
        }
        this.setState(tempData)
    }

点击提交的时候动态遍历所有的必输项,没输入则提示:

    bottomBtnClick = () => {
   
        let {
    myOptionList } = this.state
        // 动态遍历 必输项
        // 提交前判断格式中是否有必填项
        for (let key in myOptionList) {
   
            if (myOptionList[key].isrequird) {
   
                if (this.state[`${
     myOptionList[key].value}`] === '' || this.state[`${
     myOptionList[key].value}`].toString() === '[]') {
   
                    message.error(`请将${
     myOptionList[key].title}填写完整!`);
                    return false
                }

            }
        }
        console.log(this.state)
    }

全部代码:里面所有的都是使用antd组件写的,所有只看思路就ok

import React from 'react'
import {
    message } from 'antd';
import {
    withRouter } from 'react-router-dom'
import Button from '../../component/Button';
import Select from '../../component/Select';
import Input from '../../component/Input';

class Options extends React.Component {
   
    state = {
   
        myOptionList: [],
    }
    componentDidMount() {
   
        setTimeout(() => {
   
            let stateOptions = [{
   
                value: 'name',
                title: '允许传送',
                type: 'inp',
                isrequird: true
            }, {
   
                value: 'age',
                title: '允许请求',
                type: 'sel',
                isrequird: false
            }, {
   
                value: 'runing',
                title: '允许递归',
                type: 'inp',
                isrequird: true
            }]
            let newObkj = {
   }
            stateOptions.map(i => {
   
                // 到时候换成字段标识
                if (i.value === 'age') {
   
                    newObkj[i.value] = []
                } else {
   
                    newObkj[i.value] = ''
                }
            })
            this.setState({
   
                // 解构到state中
                ...newObkj,
                myOptionList: stateOptions
            })
        })

    }
    // 输入框 输入
    inputName = (type, e) => {
   
        let tempData = {
   }
        if (e.target) {
   
            tempData[type] = e.target.value
        } else {
   
            tempData[type] = e
        }
        this.setState(tempData)
    }

    bottomBtnClick = () => {
   
        let {
    myOptionList } = this.state
        // 动态遍历 必输项
        // 提交前判断格式中是否有必填项
        for (let key in myOptionList) {
   
            if (myOptionList[key].isrequird) {
   
                if (this.state[`${
     myOptionList[key].value}`] === '' || this.state[`${
     myOptionList[key].value}`].toString() === '[]') {
   
                    message.error(`请将${
     myOptionList[key].title}填写完整!`);
                    return false
                }

            }
        }
        console.log(this.state)
    }
    render() {
   
        let {
    myOptionList, } = this.state
        // 随机生成options 数组
        const children = [];
        for (let i = 10; i < 36; i++) {
   
            children.push({
    title: `${
     i.toString(36) + i}`, key: `${
     i.toString(36) + i}` });
        }
        // 必填标识  * 
        let isrequird = <a href="#!" style={
   {
    color: '#ff7875', fontSize: '12px', marginTop: '8px', marginLeft: '8px' }}>*</a>
        return (
            <div className="context" >
                <div className="search"  >
                    <div className="search-input">
                        <p className="search-input-title">{
   'XX设置'}</p>
                        <div className="search-input-row" style={
   {
    marginTop: '20px' }} style={
   {
    flexDirection: "column" }}>
                            <span style={
   {
    marginRight: '6%' }}></span>
                            <div style={
   {
    textAlign: 'right', whiteSpace: 'nowrap', display: 'flex', flexDirection: "column", justifyContent: 'space-between' }}>
                                {
   
                                    myOptionList.map((item, index) => {
   
                                        return (
                                            item.type === 'inp' ?
                                                <div key={
   index} style={
   {
    display: 'flex', marginBottom: '10px' }}>
                                                    <Input value={
   this.state[`${
     item.value}`]} title={
   `${
     item.title}`} onChange={
   (e) => this.inputName(`${
     item.value}`, e.target.value)} />
                                                    {
   item.isrequird ? isrequird : ''}
                                                </div>
                                                :
                                                item.type === 'sel' ?
                                                    <div key={
   index} className="search-input-row-element" style={
   {
    marginBottom: '10px', display: 'flex', marginLeft: '0px' }}>
                                                        <Select
                                                            title={
   `${
     item.title}:`}
                                                            showArrow={
   true}
                                                            mode="tags"
                                                            style={
   {
   }}
                                                            value={
   this.state[`${
     item.value}`]}
                                                            onChange={
   (e) => {
    this.inputName(`${
     item.value}`, e) }}
                                                            tokenSeparators={
   [',']}
                                                            options={
   children}
                                                            keyField="key"
                                                            valueField="key"
                                                            titleField="title"
                                                            dropdownMatchSelectWidth={
   true}
                                                        ></Select>
                                                        {
   item.isrequird ? isrequird : ''}
                                                    </div>
                                                    : ''
                                        )
                                    })
                                }
                            </div>
                        </div >
                    </div>
                </div>
                <div className="device_search" style={
   {
    marginLeft: "0px", marginBottom: '20px', marginTop: '20px', textAlign: "center" }}>
                    <Button Type="noIcon" title="测试按钮" onClick={
   () => this.bottomBtnClick('1')}></Button>
                    <span style={
   {
    marginRight: '20px' }}></span>
                    <Button Type="noIcon" color="#E6A23C" title="返回" onClick={
   () => this.bottomBtnClick('2')}></Button>
                </div>
            </div>
        )
    }
}
export default withRouter(Options)

在这里插入图片描述
在这里插入图片描述

目录
相关文章
|
7天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
4天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2451 13
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
3天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1489 14
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
|
1月前
|
运维 Cloud Native Devops
一线实战:运维人少,我们从 0 到 1 实践 DevOps 和云原生
上海经证科技有限公司为有效推进软件项目管理和开发工作,选择了阿里云云效作为 DevOps 解决方案。通过云效,实现了从 0 开始,到现在近百个微服务、数百条流水线与应用交付的全面覆盖,有效支撑了敏捷开发流程。
19268 29
|
1月前
|
人工智能 自然语言处理 搜索推荐
阿里云Elasticsearch AI搜索实践
本文介绍了阿里云 Elasticsearch 在AI 搜索方面的技术实践与探索。
18818 20
|
1月前
|
Rust Apache 对象存储
Apache Paimon V0.9最新进展
Apache Paimon V0.9 版本即将发布,此版本带来了多项新特性并解决了关键挑战。Paimon自2022年从Flink社区诞生以来迅速成长,已成为Apache顶级项目,并广泛应用于阿里集团内外的多家企业。
17514 13
Apache Paimon V0.9最新进展
|
5天前
|
编解码 JSON 自然语言处理
通义千问重磅开源Qwen2.5,性能超越Llama
击败Meta,阿里Qwen2.5再登全球开源大模型王座
330 11
|
1月前
|
存储 人工智能 前端开发
AI 网关零代码解决 AI 幻觉问题
本文主要介绍了 AI Agent 的背景,概念,探讨了 AI Agent 网关插件的使用方法,效果以及实现原理。
18696 17
|
2天前
|
算法 Java
JAVA并发编程系列(8)CountDownLatch核心原理
面试中的编程题目“模拟拼团”,我们通过使用CountDownLatch来实现多线程条件下的拼团逻辑。此外,深入解析了CountDownLatch的核心原理及其内部实现机制,特别是`await()`方法的具体工作流程。通过详细分析源码与内部结构,帮助读者更好地理解并发编程的关键概念。
|
2天前
|
SQL 监控 druid
Druid连接池学习
Druid学习笔记,使用Druid进行密码加密。参考文档:https://github.com/alibaba/druid
187 80