条件渲染
Recap
To pass props, add them to the JSX, just like you would with HTML attributes.
To read props, use the
function Avatar({ person, size })destructuring syntax.You can specify a default value like
size = 100, which is used for missing andundefinedprops.You can forward all props with
<Avatar {...props} />JSX spread syntax, but don’t overuse it!Nested JSX like
<Card><Avatar /></Card>will appear asCardcomponent’schildrenprop.Props are read-only snapshots in time: every render receives a new version of props.
You can’t change props. When you need interactivity, you’ll need to set state.
在 React,你可以使用 JavaScript 来控制分支逻辑。
你可以使用
if语句来选择性地返回 JSX 表达式。你可以选择性地将一些 JSX 赋值给变量,然后用大括号将其嵌入到其他 JSX 中。
在 JSX 中,
{cond ? <A /> : <B />}表示 “当cond为真值时, 渲染<A />,否则<B />”。在 JSX 中,
{cond && <A />}表示 “当cond为真值时, 渲染<A />,否则不进行渲染”。快捷的表达式很常见,但如果你更倾向于使用
if,你也可以不使用它们。