【React】:用react写了一个简单的demo:

legs+之专栏 legs+之专栏 151 人阅读 | 1 人回复 | 2026-01-08

  1. import React from 'react'
  2. import ReactDOM from 'react-dom'
  3. import asabenehImage from './images/asabeneh.jpg'

  4. // Fuction to show month date year

  5. const showDate = (time) => {
  6.   const months = [
  7.     'January',
  8.     'February',
  9.     'March',
  10.     'April',
  11.     'May',
  12.     'June',
  13.     'July',
  14.     'August',
  15.     'September',
  16.     'October',
  17.     'November',
  18.     'December',
  19.   ]

  20.   const month = months[time.getMonth()].slice(0, 3)
  21.   const year = time.getFullYear()
  22.   const date = time.getDate()
  23.   return ` ${month} ${date}, ${year}`
  24. }

  25. // Header Component
  26. const Header = ({
  27.   data: {
  28.     welcome,
  29.     title,
  30.     subtitle,
  31.     author: { firstName, lastName },
  32.     date,
  33.   },
  34. }) => {
  35.   return (
  36.     <header>
  37.       <div className='header-wrapper'>
  38.         <h1>{welcome}</h1>
  39.         <h2>{title}</h2>
  40.         <h3>{subtitle}</h3>
  41.         <p>
  42.           {firstName} {lastName}
  43.         </p>
  44.         <small>{showDate(date)}</small>
  45.       </div>
  46.     </header>
  47.   )
  48. }

  49. // TechList Component
  50. const TechList = ({ techs }) => {
  51.   const techList = techs.map((tech) => <li key={tech}>{tech}</li>)
  52.   return techList
  53. }

  54. // User Card Component
  55. const UserCard = ({ user: { firstName, lastName, image } }) => (
  56.   <div className='user-card'>
  57.     <img src={image} alt={firstName} />
  58.     <h2>
  59.       {firstName}
  60.       {lastName}
  61.     </h2>
  62.   </div>
  63. )

  64. // A button component

  65. const Button = ({ text, onClick, style }) => (
  66.   <button style={style} onClick={onClick}>
  67.     {text}
  68.   </button>
  69. )

  70. const buttonStyles = {
  71.   backgroundColor: '#61dbfb',
  72.   padding: 10,
  73.   border: 'none',
  74.   borderRadius: 5,
  75.   margin: 3,
  76.   cursor: 'pointer',
  77.   fontSize: 18,
  78.   color: 'white',
  79. }

  80. // Main Component
  81. const Main = ({ user, techs, greetPeople, handleTime }) => (
  82.   <main>
  83.     <div className='main-wrapper'>
  84.       <p>Prerequisite to get started react.js:</p>
  85.       <ul>
  86.         <TechList techs={techs} />
  87.       </ul>
  88.       <UserCard user={user} />
  89.       <Button text='Greet People' onClick={greetPeople} style={buttonStyles} />
  90.       <Button text='Show Time' onClick={handleTime} style={buttonStyles} />
  91.     </div>
  92.   </main>
  93. )

  94. // Footer Component
  95. const Footer = ({ copyRight }) => (
  96.   <footer>
  97.     <div className='footer-wrapper'>
  98.       <p>Copyright {copyRight.getFullYear()}</p>
  99.     </div>
  100.   </footer>
  101. )

  102. // The App, or the parent or the container component
  103. // Functional Component
  104. const App = () => {
  105.   const data = {
  106.     welcome: 'Welcome to 30 Days Of React',
  107.     title: 'Getting Started React',
  108.     subtitle: 'JavaScript Library',
  109.     author: {
  110.       firstName: 'Asabeneh',
  111.       lastName: 'Yetayeh',
  112.     },
  113.     date: new Date(), // date needs to be formatted to a human readable format
  114.   }
  115.   const date = new Date()
  116.   const techs = ['HTML', 'CSS', 'JavaScript']
  117.   // copying the author from data object to user variable using spread operator
  118.   const user = { ...data.author, image: asabenehImage }

  119.   const handleTime = () => {
  120.     alert(showDate(new Date()))
  121.   }
  122.   const greetPeople = () => {
  123.     alert('Welcome to 30 Days Of React Challenge, 2020')
  124.   }

  125.   return (
  126.     <div className='app'>
  127.       <Header data={data} />
  128.       <Main
  129.         user={user}
  130.         techs={techs}
  131.         handleTime={handleTime}
  132.         greetPeople={greetPeople}
  133.       />
  134.       <Footer copyRight={date} />
  135.     </div>
  136.   )
  137. }
  138. const rootElement = document.getElementById('root')
  139. ReactDOM.render(<App />, rootElement)
复制代码

源代码如上,效果图如下



数据、方法以及要渲染的内容

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

回答|共 1 个

legs+ 发表于 2026-1-9 13:06:41| 字数 2,188 | 显示全部楼层







今天,我又仿写了一个

  1. 原始代码:


  2. import React, { useState, useEffect } from 'react';
  3. import blogPost from '../../data/blog1.json';
  4. import { NavLink } from 'react-router-dom';

  5. /**
  6. * @author
  7. * @function AllPosts
  8. **/

  9. const AllPosts  = (props) => {

  10.   const [posts, setPosts] = useState([]);

  11.   useEffect(()=>{

  12.     const posts = blogPost.data;
  13.     setPosts(posts);
  14.   }, posts);

  15.   return(

  16.     <div className="row">

  17. {
  18.   posts.map(post => {

  19.     return(

  20.      


  21.       <div className="col-md-3">


  22.            <img src={post.blogImage} style={{width: "100%"}} />
  23.    
  24.     <p className="lead">
  25.     <NavLink key={post.id} to={`/post/${post.id}`}>  <div className = "post-title">{post.blogTitle}</div>  </NavLink>

  26.     </p>


  27.        </div>
  28.            
  29.      




  30.     )

  31.   })
  32. }

  33.     </div>
  34.    )

  35. }

  36. export default AllPosts
复制代码


然后,通过改写

  1. 版本A:

  2. import React from 'react';
  3. import blogPost from '../../data/blog.json';
  4. import { NavLink } from 'react-router-dom';

  5. const AllPosts = () => {
  6.   // 直接读取数据,无需 State 和 Effect
  7.   const posts = blogPost.data;

  8.   return (
  9.     <div className="row">
  10.       {posts.map((post) => (
  11.         // 1. 修正 key 的位置到最外层
  12.         <div className="col-md-3" key={post.id}>
  13.          
  14.           {/* 2. 添加 alt 属性 */}
  15.           <img
  16.             src={post.blogImage}
  17.             alt={post.blogTitle}
  18.             style={{ width: "100%" }}
  19.           />

  20.           {/* 3. 修正 HTML 嵌套,将 p 改为 div,或者直接去掉 p */}
  21.           <div className="lead">
  22.             <NavLink to={`/post/${post.id}`}>
  23.               <div className="post-title">{post.blogTitle}</div>
  24.             </NavLink>
  25.           </div>
  26.         </div>
  27.       ))}
  28.     </div>
  29.   );
  30. };

  31. export default AllPosts;


  32. 版本B:

  33. import React, { useState, useEffect } from 'react';
  34. import blogPost from '../../data/blog.json'; // 假设未来这里会被 API 替换
  35. import { NavLink } from 'react-router-dom';

  36. const AllPosts = () => {
  37.   const [posts, setPosts] = useState([]);

  38.   useEffect(() => {
  39.     // 模拟从数据源获取数据
  40.     const loadedPosts = blogPost.data;
  41.     setPosts(loadedPosts);
  42.   }, []); // 1. 修正:使用空数组作为依赖项,确保只在挂载时执行一次

  43.   return (
  44.     <div className="row">
  45.       {posts.map((post) => (
  46.         <div className="col-md-3" key={post.id}> {/* 2. 修正 key 位置 */}
  47.           <img
  48.             src={post.blogImage}
  49.             alt={post.blogTitle} // 3. 添加 alt
  50.             style={{ width: "100%" }}
  51.           />
  52.           <div className="lead"> {/* 4. 修正 HTML,p 改为 div */}
  53.             <NavLink to={`/post/${post.id}`}>
  54.               <div className="post-title">{post.blogTitle}</div>
  55.             </NavLink>
  56.           </div>
  57.         </div>
  58.       ))}
  59.     </div>
  60.   );
  61. }

  62. export default AllPosts;
复制代码


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

热门推荐