reactjs - 正常渲染表单字段与使用函数渲染
问题描述
我有两种方式呈现表单字段
第一种方法是直接将它们放入渲染中
表格.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"
}
]
}
解决方案
它实际上不会影响性能。因为如果表单的 DOM 属性没有改变,就不会有实际的 dom 操作。为了增强更多,您可以使用纯组件。制作可以更改类型和标签的自定义表单字段。有一个自定义表单域组件。
推荐阅读
- gatling - 在 gatling 中访问响应转换器内的会话变量
- javascript - 使用 Sencha 6.5.3,我如何配置一个面板,使 hideOnMaskTap 为真,透明为真?
- javascript - css中的if或case语句
- python - 在 Python 中从外部文件写入和读取特定变量
- java - Java 方法引用稳定吗?
- javascript - TypeScript 动态导入和导出
- excel - 如何使用 Aspose 从数据库中填写 excel 表
- javascript - NodeJS 是否为每个请求创建一个新线程?
- javascript - 使用 FS 从数组创建文本文件
- ssl - 将导入的自签名 SSL 证书配置到 SQL Server Express