我有一个儿童零件,可以接收至少10个道具。而且我处于多个子组件(具有不同道具)的情况。
此刻,我有类似的东西
import React from 'react'
import ChildComponent from './ChildComponent';
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
childComponentDisplayed: {
attr1: "someData",
attr2: "someData",
attr3: "someData",
attr4: "someData",
attr5: "someData",
attr6: "someData",
attr7: "someData"
// etc...
}
}
}
render() {
<ChildComponent
attr1={this.state.childComponentDisplayed.attr1}
attr2={this.state.childComponentDisplayed.attr2}
attr3={this.state.childComponentDisplayed.attr3}
attr4={this.state.childComponentDisplayed.attr4}
attr5={this.state.childComponentDisplayed.attr5}
attr6={this.state.childComponentDisplayed.attr6}
attr7={this.state.childComponentDisplayed.attr7}
></ChildComponent>
}
}
使用专用类“简化”这是一种好习惯吗?它会给出类似这样的
import React from 'react'
import ChildComponent from './ChildComponent';
class ChildComponentProps {
constructor(attr1, attr2, attr3, attr4, attr5, attr6, attr7) {
this.attr1 = attr1;
this.attr2 = attr2;
this.attr3 = attr3;
this.attr4 = attr4;
this.attr5 = attr5;
this.attr6 = attr6;
this.attr7 = attr7;
}
}
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
childComponentDisplayed: new ChildComponent(
"someData",
"someData",
"someData",
"someData",
"someData",
"someData",
"someData"
)
}
}
render() {
<ChildComponent
data={this.state.childComponentDisplayed}
></ChildComponent>
}
}
任何建议都值得赞赏
答案 0 :(得分:2)
您可以使用...
传播算子来简化它,例如
<ChildComponent {...this.state.childComponentDisplayed} />
答案 1 :(得分:0)
您可以使用此:
<ChildComponent
childComponentDisplayed={this.state.childComponentDisplayed}>
</ChildComponent>
然后在<ChildComponent>
中使用this.props.childComponentDisplayed.attrX