首页 > 解决方案 > 正常渲染表单字段与使用函数渲染

问题描述

我有两种方式呈现表单字段

第一种方法是直接将它们放入渲染中

表格.tsx

import * as React from 'react';

export interface FormProps {
}

export interface FormState {
    personal: any
}

class Form extends React.Component<FormProps, FormState> {
    constructor(props: FormProps) {
        super(props)
        this.state = {
            personal: {
                firstName: "",
                lastName: "",
            }
        }
    }

    handleChange = (event: any) => {
        let personal = { ...this.state.personal };
        personal[event.target.name] = event.target.value;
        this.setState({ personal })
    }

    render() {
        return (
            <div>
                <h1>first name</h1>
                <input type="text" name="firstName" value={this.state.personal.firstName} onChange={this.handleChange} />
                <h1>last name</h1>
                <input type="text" name="lastName" value={this.state.personal.lastName} onChange={this.handleChange} />
            </div>
        );
    }
}

export default Form;

另一种方法

表格.tsx

import * as React from 'react';

export interface FormProps {
}

export interface FormState {
    personal: any
}

class Form extends React.Component<FormProps, FormState> {
    constructor(props: FormProps) {
        super(props)
        this.state = {
            personal: {
                firstName: "",
                lastName: "",
            }
        }
    }

    count = 0;
    handleChange = (event: any) => {
        let personal = { ...this.state.personal };
        personal[event.target.name] = event.target.value;
        this.setState({ personal })
    }

    renderFields = () => {

        this.count++;
        console.log('render fields call count = ', this.count);
        return (
            <div>
                <h1>first name</h1>
                <input type="text" name="firstName" value={this.state.personal.firstName} onChange={this.handleChange} />
                <h1>last name</h1>
                <input type="text" name="lastName" value={this.state.personal.lastName} onChange={this.handleChange} />
            </div>
        )
    }

    render() {
        return (
            this.renderFields()
        );
    }
}

export default Form;

这里的问题是每次状态更改都会调用渲染字段,这是可以理解的,但这会影响我的表现

我接下来要做的是将 json 模式转换为表单,检查它是什么类型的字段,并相应地创建输入字段以及更多示例 json 的内容

"personal":{
"fields":[
  {
    "label":"name",
    "type":"text"
  },
  {
    "label":"id",
    "type":"number"
   }
]
}

标签: reactjsfunctionrender

解决方案


它实际上不会影响性能。因为如果表单的 DOM 属性没有改变,就不会有实际的 dom 操作。为了增强更多,您可以使用纯组件。制作可以更改类型和标签的自定义表单字段。有一个自定义表单域组件。


推荐阅读