导入
使用组件构建应用程序
学习如何使用 JavaScript 和 React 提升网页应用的用户体验,并实现多页面功能。
代码示例
1<!Doctype HTML> 2<html lang="en"> 3 <body> 4 <div id="root"></div> 5 </body> 6</html>
React 组件与渲染逻辑
1<script> 2 const App = () => { 3 // 返回一个包含文本 "Hello World." 的 h1 元素 4 return <h1>Hello World.</h1>; 5 } 6 7 // 通过 ID 获取根元素 ("root") 8 const rootEl = document.getElementById("root"); 9 10 // 使用 ReactDOM 将 App 组件渲染到根元素中 11 ReactDOM.render(<App />, rootEl); 12</script>
1const App = () => { 2 return <h1>Hello World</h1> 3}
No configuration found for ID: eb55f6ef8ca1a5662500efd1527794e61f5549450e7942af84d5e1560fd9bf01
创建两个 React 组件
1// Home 组件:渲染一个显示 "Home Page" 的 h1 元素 2const Home = () => { 3 return <h1>Home Page</h1>; 4} 5 6// Product 组件:渲染一个显示 "Product Page" 的 h1 元素 7const Product = () => { 8 return <h1>Product Page</h1>; 9}
根据条件渲染 Home 或 Product 组件
1const Route = ({ home }) => { 2 // 如果 'home' 为 true,则渲染 Home 组件;否则渲染 Product 组件 3 return home ? <Home /> : <Product />; 4}
渲染带有 'home' 属性的路由组件
1const App = () => { 2 const home = true; 3 4 // 使用 'home' 属性渲染 Route 组件 5 return <Route home={home} />; 6}
No configuration found for ID: 982ebc1f4ee1b9c1f15098130f51e0f55226c86bfbce6890a0dc65fff4988829