React 中的条件渲染:动态渲染 UI 元素

来源:undefined 2025-01-20 03:18:49 1031

React 条件渲染:根据条件动态显示 UI 元素

React 的条件渲染允许根据应用状态或属性有条件地渲染不同的 UI 元素或组件。本文介绍几种 React 中实现条件渲染的方法。

1. 何为条件渲染?

条件渲染是指根据特定条件来显示不同 UI 元素的技术。React 主要通过 JavaScript 表达式(例如 if 语句、三元运算符和 && 运算符)在 JSX 中实现条件逻辑。

2. 常用条件渲染技术

a. if/else 语句

这是最直接的方法,尤其在处理多个条件时非常有用。在返回 JSX 之前进行条件判断。

1

2

3

4

5

6

7

8

9

10

11

import React, { useState } from react;

const MyComponent = () => {

const [isLoggedIn, setIsLoggedIn] = useState(false);

if (isLoggedIn) {

return <h1>欢迎回来!</h1>;

} else {

return <button onClick={() => setIsLoggedIn(true)}>登录</button>;

}

};

登录后复制

b. 三元运算符

这是简写形式,用于在条件为真时显示一个元素,为假时显示另一个元素。

1

2

3

4

5

6

7

8

9

10

11

import React, { useState } from react;

const MyComponent = () => {

const [isLoggedIn, setIsLoggedIn] = useState(false);

return (

<>

{isLoggedIn ? <h1>欢迎回来!</h1> : <button onClick={() => setIsLoggedIn(true)}>登录</button>}

</>

);

};

登录后复制

c. 逻辑 && 运算符

&& 运算符是短路运算符,只有当条件为真时才渲染元素。适用于不需要 else 分支的情况。

1

2

3

4

5

6

7

8

9

10

11

12

import React, { useState } from react;

const MyComponent = () => {

const [isLoggedIn, setIsLoggedIn] = useState(false);

return (

<>

{isLoggedIn && <h1>欢迎回来!</h1>}

{!isLoggedIn && <button onClick={() => setIsLoggedIn(true)}>登录</button>}

</>

);

};

登录后复制

对于复杂的条件逻辑,使用函数可以提高代码的可读性和可维护性。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import React, { useState } from react;

const MyComponent = () => {

const [status, setStatus] = useState(loading);

const renderContent = () => {

switch (status) {

case loading: return <p>加载中...</p>;

case error: return <p>发生错误!</p>;

case success: return <p>数据加载成功!</p>;

default: return null;

}

};

return (

<div>

{renderContent()}

<button onClick={() => setStatus(error)}>模拟错误</button>

<button onClick={() => setStatus(success)}>模拟成功</button>

</div>

);

};

登录后复制

4. 使用 React 组件进行条件渲染

根据条件渲染整个组件。

1

2

3

4

5

6

7

8

9

10

import React, { useState } from react;

const Welcome = () => <h1>欢迎回来!</h1>;

const Login = () => <button>登录</button>;

const MyComponent = () => {

const [isLoggedIn, setIsLoggedIn] = useState(false);

return isLoggedIn ? <Welcome /> : <Login />;

};

登录后复制

5. 基于数组映射的条件渲染

对数组元素进行条件渲染。

1

2

3

4

5

6

7

8

9

10

11

12

13

import React from react;

const items = [

{ id: 1, name: 商品 1, available: true },

{ id: 2, name: 商品 2, available: false },

{ id: 3, name: 商品 3, available: true },

];

const ItemList = () => (

<ul>

{items.map((item) => item.available && <li key={item.id}>{item.name}</li>)}

</ul>

);

登录后复制

6. 使用 useEffect 进行 API 调用的条件渲染

处理 API 调用结果的条件渲染。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import React, { useState, useEffect } from react;

const DataFetchingComponent = () => {

const [data, setData] = useState(null);

const [loading, setLoading] = useState(true);

const [error, setError] = useState(null);

useEffect(() => {

fetch(https://api.example.com/data)

.then(response => response.json())

.then(data => {

setData(data);

setLoading(false);

})

.catch(err => {

setError(err);

setLoading(false);

});

}, []);

if (loading) return <p>加载中...</p>;

if (error) return <p>错误: {error.message}</p>;

return <div>{JSON.stringify(data)}</div>;

};

登录后复制

7. 条件渲染最佳实践

保持简洁,避免嵌套过深。 使用辅助函数处理复杂逻辑。 充分利用状态和属性。

8. 总结

条件渲染是 React 中一项重要的技术,通过灵活运用以上方法,可以构建更动态和用户友好的界面。选择最适合你项目结构和复杂程度的方法。

以上就是React 中的条件渲染:动态渲染 UI 元素的详细内容,更多请关注php中文网其它相关文章!

最新文章