我想有條件地在我的頁面上顯示幾條消息。以下是我的實際場景的簡化代碼。有條件的渲染與三元運算符在反應
<div>
{
isCondition1 == true ?
'Show issue list'
:
isConditionA == true?
'Show message for condition A'
:
'Show error message'
}
</div>
<div>
{
isCondition2 == true?
'Show team issue list'
:
isConditionA == true?
'Show message for condition A'
:
'Show error message'
}
</div>
我想從上面拿出常見的東西,並在代碼中使用它。
const msgNoIssues = (
isConditionA == true?
'Show message for condition A'
:
'Show error message'
);
而且按如下方式使用它:
<div>
{
isCondition1 == true?
'Show issue list'
:
{msgNoIssues}
}
</div>
<div>
{
isCondition2 == true ?
'Show team issue list'
:
{msgNoIssues}
}
</div>
但它給了一個錯誤信息:
Objects are not valid as a React child (found: object with keys {msgNoIssues}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.
能把它沒有反應插件可以實現嗎?有沒有更好的方法來做到這一點?