我有一个通过Material-ui创建的以下文本。
<TextField
error = {this.props.projectNameErrorStatus}
required = {this.props.projectNameRequiredStatus}
className={classes.textField}
margin="normal"
id="projectName"
name="projectName"
/>
但是,我有4个不同的TextField,我将使用它们的不同名称为它们设置错误道具,这些名称带有父容器的状态。这个问题将迫使我使用8种不同的道具和州名。这将使我的代码更大,可读性更差。 例如,我必须启动状态:
state = {
projectNameErrorStatus :true,
NameErrorStatus :true,
FamilyErrorStatus :true,
EmailErrorStatus :true,
projectNameRequiredStatus: true,
NameRequiredStatus: true,
FamilyRequiredStatus: true,
EmailRequiredStatus: true,
}
state = {this.state}
,然后将它们作为道具传递给子组件。之后,我应该将它们全部用作道具。
let {
state = {
projectNameErrorStatus,
NameErrorStatus,
FamilyErrorStatus,
EmailErrorStatus,
projectNameRequiredStatus,
NameRequiredStatus,
FamilyRequiredStatus,
EmailRequiredStatus
} = this.props.state
我能以更清洁,更有效的方式拥有这些道具和状态吗?
答案 0 :(得分:0)
将其拆分为两个组件并使用json对象:
import React from 'react';
class customTextfield extends Component {
render() {
return (
<TextField
error={this.props.ErrorStatus}
required={this.props.RequiredStatus}
className={classes.textField}
margin="normal"
id={this.props.Name}
name={this.props.Name}
label={this.props.Label} />
);
}
}
class parentContainer extends Component {
constructor(props) {
super(props);
this.state = {
ErrorStatus = {
Name: true,
Email: false,
Project: false,
Family: false
},
RequiredStatus = {
Name: true,
Email: true,
Project: true,
Family: false
},
listOfTextFields =["Name", "Email", "Project", "Family"]
}
}
render() {
return this.state.listOfTextFields.map(field => <customTextfield Name={field} Label={field} ErrorStatus={this.state.ErrorStatus[field]} RequiredStatus={this.state.RequiredStatus[field]} />)
};
}