手册
目录
在 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} />);
运行实例 »
&&运算符另一种有条件地渲染 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 等于 true,则将呈现 && 之后的表达式。
尝试清空 cars 数组:
const cars = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);
运行实例 »
另一种有条件地渲染元素的方法是使用三元运算符。
condition ? true : false
我们将回到目标示例。
如果isGoal是true,则返回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} />);
运行实例 »
要了解更多信息,请参阅三元运算符部分。
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.3万人学习
共49课时
77.4万人学习
共29课时
62万人学习
共25课时
39.5万人学习
共43课时
71.3万人学习
共25课时
61.9万人学习
共22课时
23.1万人学习
共28课时
34.1万人学习
共89课时
125.8万人学习