我在代码中使用了一堆文本字段,我想映射它们而不是多次编写它们。但是,我无法执行此操作,因为我的文本字段还需要构造函数props中的元素。
import React, { Component, useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import PermanentDrawerLeft from '../../components/drawer/drawer';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
export default class AddUserPage extends Component <{}, { firstName: string, lastName: string, email: string,phone: string,password: string }>{
constructor(props: Readonly<{}>) {
super(props);
this.state = {
firstName: '',
lastName: '',
phone: '',
email: '',
password: '',
};
}
render() {
return (
<div>
<PermanentDrawerLeft></PermanentDrawerLeft>
<div className='main-content'>
<form className="form" noValidate autoComplete="off">
{
<TextField id="outlined-basic" label="First Name" variant="outlined" onChange={e => {
this.setState({firstName: e.target.value})
}}/>
</form>
</div>
</div>
);
}
}
如果我使用以下映射:
{
[{ label: 'First Name', state: this.state.firstName }].map((item, index) => (
<TextField
id="outlined-basic"
label={item.label}
variant="outlined"
onChange={e => this.setState({ [item.state]: e.target.value })}
/>
))
}
我在最后一行收到此错误:
Argument of type '{ [x: string]: string; }' is not assignable to parameter of type '{
代码沙箱: https://codesandbox.io/s/goofy-cray-o87fm?fontsize=14&hidenavigation=1&theme=dark
答案 0 :(得分:1)
第二个代码段显示出一些语法问题:
firstName
括在对象文字([{label: 'First Name', state: 'firstName'}]
)中的花括号中this.setState({[item.state]: e.target.value})
因此,您应该尝试的代码看起来像这样:
{
[{label: "First Name", state: 'firstName'}].map(item, index) => (
<TextField
id="outlined-basic"
key={index}
label={item.label}
variant="outlined"
onChange={e => this.setState({[item.state]: e.target.value} as any)}
/>
))
}
p.s。这些是我可以在不了解更广泛的代码上下文的情况下得出的结论