React 条件渲染
在 React 中,可以有条件地渲染组件。
有几种方法可以做到这一点。
if 语句
我们使用 if JavaScript 运算符来决定要渲染的组件。
实例:
我们将使用这两个组件:
function MissedGoal() {return <h2>MISSED!</h2>;}function MadeGoal() {return <h2>Goal!</h2>;}
实例:
现在,我们将创建另一个组件,该组件根据条件选择要渲染的组件:
import React from 'react';import ReactDOM from 'react-dom';function MissedGoal() {return <h2>MISSED!</h2>;}function MadeGoal() {return <h2>GOAL!</h2>;}function Goal(props) {const isGoal = props.isGoal;if (isGoal) {return <MadeGoal/>;}return <MissedGoal/>;}ReactDOM.render(<Goal isGoal={false} />,document.getElementById('root'));
尝试将 isGoal 属性更改为 true:
实例:
import React from 'react';import ReactDOM from 'react-dom';function MissedGoal() {return <h2>MISSED!</h2>;}function MadeGoal() {return <h2>GOAL!</h2>;}function Goal(props) {const isGoal = props.isGoal;if (isGoal) {return <MadeGoal/>;}return <MissedGoal/>;}ReactDOM.render(<Goal isGoal={true} />,document.getElementById('root'));
逻辑 && 运算符
有条件地渲染 React 组件的另一种方法是使用 && 操作符。
Example:
我们可以使用大括号在 JSX 中嵌入 JavaScript 表达式:
import React from 'react';import ReactDOM from 'react-dom';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'];ReactDOM.render(<Garage cars={cars} />,document.getElementById('root'));
如果 cars.length 等于 true,则将展示 && 之后的表达式。
尝试清空 cars 数组:
实例:
import React from 'react';import ReactDOM from 'react-dom';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 = [];ReactDOM.render(<Garage cars={cars} />,document.getElementById('root'));
三元运算符
有条件地渲染元素的另一种方法是使用三元运算符。
condition ? true : false
我们将回到 Goal 示例。
实例:
如果 isGoal 为 true,则返回 MadeGoal 组件,否则返回 MissedGoal 组件:
import React from 'react';import ReactDOM from 'react-dom';function MissedGoal() {return <h2>MISSED!</h2>;}function MadeGoal() {return <h2>GOAL!</h2>;}function Goal(props) {const isGoal = props.isGoal;return (<>{ isGoal ? <MadeGoal/> : <MissedGoal/> }</>);}ReactDOM.render(<Goal isGoal={false} />,document.getElementById('root'));
想学习更多, 可以查看 三元运算符 章节。