gpt4 book ai didi

javascript - 在 react 中使用三元运算符进行条件渲染

转载 作者:行者123 更新时间:2023-11-29 23:38:33 36 4
gpt4 key购买 nike

我正在尝试有条件地在我的页面上呈现几条消息。以下是我实际场景的简化代码。

<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.

不加react插件能实现吗?有没有更好的方法?

最佳答案

When {} is needed in JSX?

我们需要使用 {} 将 js 表达式放在 JSX 中,所以将三元运算符放在 {} 中。

Reason of this error: Objects are not valid as a React child

{ msgNoIssues } 的含义是 { msgNoIssues: msgNoIssues } 这意味着您正在尝试使用键 msgNoIssues 渲染对象,这就是为什么它抛出错误:对象作为 React 子项无效(已找到:具有键 {msgNoIssues} 的对象)。

解决方案:

去掉msgNoIssues周围的{},这样写:

<div>
{
isCondition1 == true ?
'Show issue list'
:
msgNoIssues
}
</div>
<div>
{
isCondition2 == true ?
'Show team issue list'
:
msgNoIssues
}
</div>

检查此代码段({ a } 的含义):

let a = 10;

let obj = {a};

console.log('obj = ', obj);

查看文档:Embedding Expressions in JSXConditional Rendering

关于javascript - 在 react 中使用三元运算符进行条件渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45815203/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com