javascript - 了解 && 在 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>
)
解决方案
您将此问题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了解更多信息细节。
推荐阅读
- javascript - 如何在 Angular 中获取数据模型的类名?
- momentjs - 如何获取工作日的列表名称?
- amazon-s3 - boto3 put metadata清空对象内容
- botframework - Directline/Web 聊天频道错误:HTTP 状态码 Forbidden
- reactjs - 如何在 React Native 中创建可拖动组件?
- oauth-2.0 - OneLogin:以编程方式获取 JWT 令牌
- java - 面临无法访问其他 .html 文件的问题
- javascript - 无法从 lambda 列出阶跃函数标签
- angular - 带有 @Component 装饰器的 Angular Injectable() 装饰器
- c - 了解 Azure IoT Edge 模块