ReactJS - 组件
ReactJS - 组件
Section titled “ReactJS - 组件”在本教程中,我们将探索如何在 React 中创建和组合组件。这种模块化方法使你的应用更容易开发、测试和维护,允许你更新单独的组件而不会影响页面的其余部分。
函数组件示例(默认无状态)
Section titled “函数组件示例(默认无状态)”现代 React 开发主要依赖于函数组件。它们是接受 props (属性) 作为参数并返回 React 元素的 JavaScript 函数。我们来看一个例子,其中 App 是父组件,渲染 Header 和 Content 子组件。只有 App 组件需要被导出才能进行渲染。
App.jsx
Section titled “App.jsx”import React from 'react';
// Functional component for Headerfunction Header() { return ( <div> <h1>Header</h1> </div> );}
// Functional component for Contentfunction Content() { return ( <div> <h2>Content</h2> <p>The content text!!!</p> </div> );}
// Functional component for App (Parent)function App() { return ( <div> <Header /> <Content /> </div> );}
export default App;要在页面上渲染这个 App 组件,我们需要将它导入到我们的主入口文件(例如 main.js 或 index.js)中,并使用 react-dom/client 的 createRoot API。
main.js (或 index.js)
Section titled “main.js (或 index.js)”import React from 'react';import { createRoot } from 'react-dom/client';import App from './App.jsx';
const container = document.getElementById('app');const root = createRoot(container);root.render(<App />);上述代码将渲染一个页面,显示一个“Header”部分和一个“Content”部分,其中包含文本“The content text!!!”。
有状态函数组件示例(使用 Hooks)
Section titled “有状态函数组件示例(使用 Hooks)”函数组件可以使用 React Hooks(例如 useState)来管理状态。在此示例中,App 组件将持有状态(一个数据数组),并将这部分数据作为 props 传递给子组件。我们将动态地渲染 TableRow 组件列表。我们使用现代 JavaScript 语法 (ES6+),例如箭头函数,以获得更简洁的代码。
App.jsx
Section titled “App.jsx”import React, { useState } from 'react';
// Header component (can be in a separate file)const Header = () => { return ( <div> <h1>Header</h1> </div> );}
// TableRow component (can be in a separate file)const TableRow = (props) => { return ( <tr> <td>{props.data.id}</td> <td>{props.data.name}</td> <td>{props.data.age}</td> </tr> );}
// App component (Parent with state)const App = () => { const [data, setData] = useState([ { "id": 1, "name": "Alice", "age": "30" }, { "id": 2, "name": "Bob", "age": "24" }, { "id": 3, "name": "Charlie", "age": "35" } ]);
return ( <div> <Header /> <table> <tbody> {data.map((person, i) => ( <TableRow key={person.id} data={person} /> ))} </tbody> </table> </div> );}
export default App;main.js (或 index.js) - 入口文件
Section titled “main.js (或 index.js) - 入口文件”import React from 'react';import { createRoot } from 'react-dom/client';import App from './App.jsx';
const container = document.getElementById('app');const root = createRoot(container);root.render(<App />);关于 key 属性的注意:
Section titled “关于 key 属性的注意:”请注意在 map() 函数中使用了 key={person.id}。在渲染元素列表时,为每个项提供一个唯一的 key 属性至关重要。这有助于 React 识别哪些项已更改、已添加或已移除,从而实现更高效的更新并避免组件状态和性能的潜在问题。最好使用数据中稳定、唯一的 ID 作为 key。将数组索引 i 用作 key 应该是最后的选择,并且仅在列表是静态的且项不会重新排序时使用。
此设置将渲染一个“Header”,后跟一个表格,列出人员的 ID、姓名和年龄。