我是反应编程的新手,我想知道如何根据共享相同类的某些条件来呈现内容。
下面是我的代码,
render = () => {
const data = this.props.data;
return <div className="wrapper">
{this.data.status === 'ready' && this.state.missing &&
<div className="unknown">
<div className="status missing">content1</div>
</div>
}
{this.data.status === 'incomplete' &&
<div className="unknown">
<div className="status incomplete">content2</div>
</div>
}
{this.data.status === 'failed' &&
<div className="unknown">
<div className="status failed">content 3</div>
</div>
}
}
我该如何重构以上代码。我觉得这是重复的。有人可以帮我吗谢谢。
答案 0 :(得分:1)
您能否详细说明一下条件?您是否一直在比较某个输入(在这种情况下,添加嵌套的switch
语句可能会有所帮助,还是每个条件都使用新变量?
假设您的条件是独立的,则可以对此类元素使用生成器函数:
getStatusComponent = (statusClass,content) => {
return (
<div className="unknown">
<div className={'status' + statusClass}>{content}</div>
</div>
)
}
render = () => {
const data = this.props.data;
return <div className="wrapper">
{condition_1 && condition_2 && getStatusComponent('missing',content1)}
{condition_3 && getStatusComponent('incomplete',content2)}
{condition_4 && getStatusComponent('failed',content3)}
}
答案 1 :(得分:1)
这对IMO来说还算不错。这种模式相当普遍。您可能会合并所有案例共有的div。
render = () => {
const data = this.props.data;
return <div className="wrapper">
<div className="unknown">
{condition_1 && condition_2 &&
<div className="status missing">content1</div>
}
{condition_3 &&
<div className="status incomplete">content2</div>
}
{condition_4 &&
<div className="status failed">content 3</div>
}
</div>
}
如果content1和content2等确实很冗长,并且您不希望这样做,则可以考虑查看它们共享多少标记,并简单地交换其中的某些部分。换句话说,将条件检查移到树的尽头。
const getClassname = (condition_1, condition_2, condition_3, condition_4) => {
if (condition_1 && condition_2) { return 'status missing' }
if (condition_3) { return 'status incomplete' }
if (condition_4) { return 'status failed' }
return null;
}
render = () => {
const data = this.props.data;
return <div className="wrapper">
<div className="unknown">
<div className={getClassname(condition_1, condition_2, condition_3, condition_4)}>
content {/*you now need to decide how to generate content. You can make a `getContent` function, or perhaps do more swapping on a case-by-case basis. It depends on your content*/}
</div>
</div>
}