[英]How to render a different element based on a condition (react jsx)
I want to show a certain button inside a data table in the UI based on a condition我想根据条件在 UI 的数据表中显示某个按钮
pseudocode伪代码
if assessment.category is complete
//show success button
if assessment.category is not complete
//show failed button
if assessment.category is in progress
//show in progress button
if assessment.category is rejected
//show rejected button
(JSX) (JSX)
<td>
{assessment.categoryCategory === 'Complete' && <button type="button" className="btn btn-success">Complete</button>
}
{assessment.categoryCategory === 'Not Complete' && <button type="button" className="btn btn-info">Not Completed</button>
}
{assessment.categoryCategory === 'In Progress' && <button type="button" className="btn btn-warning">WIP</button>
}
{assessment.categoryCategory === 'Rejected' && <button type="button" className="btn btn-danger">Rejected</button>
}
</td>
However this is wrong.然而这是错误的。 It throws an error.它抛出一个错误。 Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
<td>
{
assessment.categoryCategory === 'Complete' ? (
<button type="button" className="btn btn-success">Complete</button>
) : (
<button type="button" className="btn btn-info">Not Completed</button>
)
}
</td>
Why not simplify it like this?为什么不把它简化成这样?
<td>
<button type="button" className={assessment.categoryCategory === 'Complete' ? "btn btn-success" : "btn btn-info"}>
{assessment.categoryCategory === 'Complete' ? "Complete" : "Not Complete"}
</button>
</td>
const btnMap = {
complete = { key: 'warning', label: 'Completed' };
'not complete' = { key: 'info', label: 'Not Completed' };
progress = { key: 'warning', label: 'WIP'};
rejected = { key: 'danger', label: 'Rejected' };
// easy to add additional values if needed.
}
const btnItem = btnMap[assestment.category || 'not progress']; //set a default value if you believe could be undefined.
<button
type="button"
className={`btn btn-${btnItem.key}`}>
{btnItem.label}
</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.