Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

React 条件渲染


在 React 中,您可以有条件地渲染组件。

有几种方法可以做到这一点。


if 语句

我们可以使用 if JavaScript 运算符来决定渲染哪个组件。

示例

我们将使用这两个组件

function MissedGoal() {
  return <h1>MISSED!</h1>;
}

function MadeGoal() {
  return <h1>Goal!</h1>;
}

示例

现在,我们将创建另一个组件,根据条件选择渲染哪个组件

function Goal(props) {
  const isGoal = props.isGoal;
  if (isGoal) {
    return <MadeGoal/>;
  }
  return <MissedGoal/>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);

运行示例 »

尝试将 isGoal 属性更改为 true

示例

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={true} />);

运行示例 »


w3schools CERTIFIED . 2022

获得认证!

完成 React 模块,完成练习,参加考试并成为 w3schools 认证人员!!

$95 报名

逻辑 && 运算符

另一种有条件地渲染 React 组件的方法是使用 && 运算符。

示例

我们可以使用花括号在 JSX 中嵌入 JavaScript 表达式

function Garage(props) {
  const cars = props.cars;
  return (
    <>
      <h1>Garage</h1>
      {cars.length > 0 &&
        <h2>
          You have {cars.length} cars in your garage.
        </h2>
      }
    </>
  );
}

const cars = ['Ford', 'BMW', 'Audi'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

运行示例 »

如果 cars.length > 0 等于 true,则 && 后面的表达式将渲染。

尝试清空 cars 数组

示例

const cars = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

运行示例 »


三元运算符

另一种有条件地渲染元素的方法是使用三元运算符。

condition ? true : false

我们将回到目标示例。

示例

如果 isGoaltrue,则返回 MadeGoal 组件,否则返回 MissedGoal 组件

function Goal(props) {
  const isGoal = props.isGoal;
  return (
    <>
      { isGoal ? <MadeGoal/> : <MissedGoal/> }
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);

运行示例 »

要了解更多信息,请参阅 三元运算符 部分。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.