我有一个如下所示的IF语句,其中JSX参数(如果它们被称为)在每种情况下是相同的,唯一的区别是呈现的组件:
if (type === 'currencySalaryBonus') {
return <CurrencySalaryBonus key={questionID} data={this.props.data} answer={this.props.answer} nextStepCallback={this.props.nextStepCallback} showTitle={this.props.showTitle} />;
} else if (type === 'age') {
return <Age key={questionID} data={this.props.data} answer={this.props.answer} nextStepCallback={this.props.nextStepCallback} showTitle={this.props.showTitle} />;
} else if (type === 'name') {
return <Name key={questionID} data={this.props.data} answer={this.props.answer} nextStepCallback={this.props.nextStepCallback} showTitle={this.props.showTitle} />;
}
.... the list goes on
我想知道是否有一些语法糖,我不知道这意味着我可以做类似的事情
if (type === 'currencySalaryBonus') {
return <CurrencySalaryBonus {object} />;
} else if (type === 'age') {
return <Age {object} />;
}
.....
或任何其他方式,我可以使这不那么可怕 - 这个IF声明有大约30个条件。
非常感谢你的帮助!
我正在使用带有Babel - ES6 / 7的Webpack,如果有帮助,可以使用更现代的功能。
答案 0 :(得分:2)
你几乎得到了它。只需要添加扩展运算符:
if (type === 'currencySalaryBonus') {
return <CurrencySalaryBonus {...object} />;
} else if (type === 'age') {
return <Age {...object} />;
}
这将传播 object
的所有属性到每个组件上。
答案 1 :(得分:1)
object = {
key: questionID,
data: this.props.data,
answer: this.props.answer,
nextStepCallback: this.props.nextStepCallback,
showTitle: this.props.showTitle
};
然后做
return <Age {...object} />;
答案 2 :(得分:1)
传播是一个很好的选择,但为了完整性,这也是另一个建议。
let Component;
if (type === 'currencySalaryBonus') {
Component = CurrencySalaryBonus;
} else if (type === 'age') {
Component = Age;
}
return React.createElement(Component, { key: questionID, data: this.props.data });