Javascript 当道具也被传递时,我如何映射元素?
我在代码中使用了一堆文本字段,我希望映射它们,而不是多次编写它们。但是,我无法这样做,因为我的文本字段也需要构造函数道具中的元素Javascript 当道具也被传递时,我如何映射元素?,javascript,reactjs,typescript,mapping,material-ui,Javascript,Reactjs,Typescript,Mapping,Material Ui,我在代码中使用了一堆文本字段,我希望映射它们,而不是多次编写它们。但是,我无法这样做,因为我的文本字段也需要构造函数道具中的元素 import React, { Component, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; import PermanentDrawerLef
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>
);
}
}
代码沙盒:
我发现您的第二个代码片段存在一些语法问题:
- 您不应该将
包装到对象文本中的大括号中(firstName
)[{label:'firstName',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)}
/>
))
}
{
[{label:“firstName”,state:“firstName”}]。映射(项,索引)=>(
this.setState({[item.state]:e.target.value}如有)}
/>
))
}
p、 这些都是我在没有看到更广泛的代码上下文的情况下可以得出的结论这并不完全有效,你能在我更新的qs中看到代码吗?如果我写了,state:firstName,我得到的错误是找不到name firstName。所以我把它改成了这个。state。firstName,但这不起作用。这只是为了提供信息。我修复了名未找到的问题,但我仍然得到更新的qsNope中提到的一个,这也不起作用。你可以在这个代码沙盒上试试吗。谢谢@x89:只需稍作更改—没有错误,没有问题。检查叉子。
Argument of type '{ [x: string]: string; }' is not assignable to parameter of type '{
{
[{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)}
/>
))
}