繁体   English   中英

如何使用三元条件使用 React 渲染 jsx?

[英]How to use ternary condition to render jsx using react?

如果某些条件为真,我想返回 jsx 如果不应该返回未定义。

下面是我的代码,

const showInfo = (item) {
    return (
        <div>
            <div>
                <span>name</span>
            </div>
            <div>
                <button>click</button>
            </div>
        </div>
    );
}
    
const Parent = () => {
    return (
        <Child
            onDone = {({item}) => {
                notify ({
                    actions: (condition === 'value1' || condition === 'value2' ) &&
                        showInfo(item) //should put this condition into showInfo method
                })
            }}
         />
     );
 }
   

我想做什么? 上面的代码有效。 但现在我想将条件放在 showInfo 方法中。 因此,如果条件为真,则返回 jsx,如果条件为假,则应返回未定义。

我试过什么? 我已经尝试过类似下面的东西

const showInfo = (item) {
    return 
        {(condition === 'value1' || condition === 'value2' ) ? <div>
            <div>
                <span>name</span>
            </div>
            <div>
                <button>click</button>
            </div>
        </div>
        : undefined
    }
    );
}
    
const Parent = () => {
    return (
        <Child
            onDone = {({item}) => {
                notify ({
                    actions: showInfo(item) //error here
                })
            }}
         />
     );
 }

但是上面尝试过的代码在操作语句中给出错误“类型'void'不可分配给类型'ReactNode'”。

有人可以帮我解决这个问题。 我不确定我是否正确使用了三元运算符。 谢谢。

编辑

在尝试了提供的答案之一之后,

notify 是一个从 usehook 返回的方法,它对下面的组件求值

const Something: React.FC<SomethingProps> = ({
    description,
    actions,
    ...props
}) =>
    (
        <Header>
            <Title>{title}</Title>
        </Header>
        {(description ||actions) && (
            <Body> //this is displayed
                {description && <Description>{description}</Description>}
                {actions && <Actions>{actions}</Actions>}
            </Body>
        )}
    );

此处在 showInfo 组件中条件失败时显示该组件。

在 showInfo 中,如果条件失败,我将返回未定义但仍然在 Something 组件中,即使我有 {description || 行动}

我不确定这里发生了什么。在这种情况下我必须检查不显示的操作的条件是什么

我努力了

{(description ||actions !== 'false') && (
    <Body> //this is displayed
        {description && <Description>{description}</Description>}
        {actions && <Actions>{actions}</Actions>}
    </Body>
)}

这有效。 我想知道为什么我要特别提到

actions !== 'false' 

而不是行动,只有有人可以帮助我解决这个问题。 谢谢。

如果您想从 function 返回 jsx,您应该将它们包装在某个组件中。 在这种情况下,您可以使用<React.Fragment>或仅使用<> 我可以看到的另一个问题是您可能忘记了箭头 function 中的箭头。 也不知道变量名condition从何而来。

const showInfo = (item) => {
    return (
      <>
        { condition === "value1" || condition === "value2" ? (
          <div>
            <div>
              <span>name</span>
            </div>
            <div>
              <button>click</button>
            </div>
          </div>
        ) : undefined}
      </>
    );
  };

使用 useState 或 useEffect 钩子不是更好吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM