【问题标题】:How do I write a an If statement in a react component?如何在反应组件中编写 If 语句?
【发布时间】:2022-06-16 23:24:03
【问题描述】:

我是 react 新手,我正在使用碳反应库,我只是想知道如何在 map 函数中添加 if 语句。

它只是像普通字符串一样写入 if 语句。

<StructuredListBody>
{matchingResults?.map((X, i) =>
<StructuredListRow}>
{if (X?.status.includes(Working)){
<StructuredListCell>{X?.status}</StructuredListCell>}
else 
{<StructuredListCell>{X?.checking}</StructuredListCell>}};
</StructuredListRow>
)}
</StructuredListBody>

--- 附加信息 我简化了代码,但我认为不能使用三元运算符,因为会有两个以上的条件。

更像是这样我仍然不明白如何返回组件中的特定组件。我正在尝试更改颜色。唯一想到的就是再次使用相同的东西

    <StructuredListBody>
    {matchingResults?.map((X, i) =>
    <StructuredListRow key={`row-${row.id} -${i}`}>
    if (X?.status.includes(Working) {                                                
  <StructuredListCell key={`cell-${row.id}} noWrap style={{paddingBottom: '.5rem', color: 'red'}}>
    {X?.status}
    </StructuredListCell>}
    else 
    {<StructuredListCell key={`cell-${row.id} noWrap style={{paddingBottom: '.5rem', color: 'yellow'}}>
    {X?.status}
    </StructuredListCell>}
     )}
     </StructuredListBody>
 

【问题讨论】:

  • 这能回答你的问题吗? if-else statement inside jsx: ReactJS
  • 当你有一个没有大括号的箭头函数时,函数“内部”的所有东西都是返回值。如果要执行 if 然后手动返回,请添加大括号(和 return 语句)
  • 使用三元运算符

标签: javascript reactjs


【解决方案1】:

由于渲染的唯一区别是StructuredListCell 组件中的内容。对于您的情况,最简单的方法是使用三元运算符 (?),此外,关键道具必须是唯一的,我在这里使用了索引,但您应该在数据结构中使用唯一的东西。

        <StructuredListBody>
            {matchingResults.map((X, i) => (
                <StructuredListRow key={i}>
                    <StructuredListCell>{X?.status.includes(Working) ? X?.status : X?.checking}</StructuredListCell>
                </StructuredListRow>
            ))}
        </StructuredListBody>

阅读更多关于Conditional Rendering in React

【讨论】:

  • 当代码以附加信息中的方式编写时,我仍然不明白
  • 你也可以在 style 属性中使用三元,不一定需要 if 语句
【解决方案2】:

有几种方法可以在反应组件的渲染部分使用 if 语句。您可以根据如下逻辑有条件地渲染不同的组件:

<StructuredListBody>
    {matchingResults?.map((X, i) => {
        if (X?.status.includes(Working)) {
            return (
                <StructuredListRow>
                    <StructuredListCell>{X?.status}</StructuredListCell>
                </StructuredListRow>
            );
        } else {
            return (
                <StructuredListCell>{X?.checking}</StructuredListCell>
            );
        }
    })}
</StructuredListBody>

或者你可以在组件内部做逻辑:


<StructuredListBody>
    {matchingResults?.map((X, i) => (
        <StructuredListCell>
            {X?.status.includes(Working) ? X?.status : X?.checking}
        </StructuredListCell>
    ))}
</StructuredListBody>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 2021-10-13
    • 2011-08-08
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多