首页 > 解决方案 > 了解 && 在 React 组件中的使用

问题描述

我试图在反应中理解这个功能组件。我知道 Post 接受两个参数 post 和 excerpt。使用了 2 个三元运算符

这是使用 post 的组件的渲染代码。

        const renderPosts = () => {
            if (loading) return <p>Loading posts...</p>
            if (hasErrors) return <p>Unable to display posts.</p>

            return posts.map(post => <Post key={post.id} post={post} excerpt />)
        }

我不明白(摘录&&)与下面的链接一起在做什么。你能给我解释一下吗?还传递了上面地图助手的摘录,这意味着什么?它没有价值。

        export const Post = ({ post, excerpt }) => (
          <article className={excerpt ? 'post-excerpt' : 'post'}>
            <h2>{post.title}</h2>
            <p>{excerpt ? post.body.substring(0, 100) : post.body}</p>

            {excerpt && (
              <Link to={`/posts/${post.id}`} className="button">
                View Post
              </Link>
            )}
          </article>
        )

标签: javascriptreactjs

解决方案


您将此问题reactjs作为唯一标签发布,表明您认为这是一react件事,但基本上您的问题是关于一javascript件事:“短路条件”。

从您发布的代码中:

excerpt && <Link ...>

正在表达

if excerpt 
  then return <Link ...> 
  else return undefined

因此,如果excerpt评估为“虚假”,则不会显示任何内容(因为React 忽略了 undefined 或 null),但如果excerpt为“真实”,则将显示链接。


编辑:

我刚刚注意到你有第二个问题:

还传递了上面地图助手的摘录,这意味着什么?它没有价值。

省略属性的值会导致 JSX 将其视为 true。请在其他地方查看此SO 答案

所以那段代码表示它希望Post组件始终添加链接。

请注意,您的第二个问题实际上是特定于反应的,因为当 HTML 的默认行为将它们视为“虚假”时,React 不遗余力地将这些“空”属性定义为“真实” - 请参阅this SO answer了解更多信息细节。


推荐阅读