学习库ReactConditional Rendering

Conditional Rendering

Show, replace, or omit interface branches with normal JavaScript decisions.

更新于 适用于 React 19.2

React uses JavaScript conditions to choose which element tree to return. Prefer branches that make each visible state explicit.

Branch before returning

Progress.tsx
function Progress({ loading, error, percent }) {
  if (loading) return <p>Loading progress…</p>;
  if (error) return <p role="alert">Progress could not be loaded.</p>;
  return <p>{percent}% complete</p>;
}

Early returns work well for loading, error, empty, and permission states.

Inline choices

CourseCard.tsx
<strong>{complete ? "Review course" : "Start learning"}</strong>
{prerequisite && <p>Recommended first: {prerequisite}</p>}

Use a ternary when both outcomes render something and && when false should render nothing. Avoid long nested ternaries.

Keep this

Model every meaningful UI state, use early returns for major branches, and keep inline conditions short.

学习位置已保存在此设备上。