当前位置:首页 > React

react.js如何编写

2026-01-24 19:11:26React

编写 React.js 的基本步骤

安装 Node.js 和 npm
确保系统中已安装 Node.js 和 npm(Node.js 自带 npm)。可以通过以下命令检查版本:

node -v
npm -v

创建 React 项目
使用 create-react-app 工具快速生成项目结构:

npx create-react-app my-app
cd my-app
npm start

组件开发

函数组件
函数组件是 React 中最简单的组件形式:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

类组件
类组件支持状态和生命周期方法:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

状态管理

使用 useState Hook
函数组件中通过 Hook 管理状态:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

类组件中的状态
类组件通过 this.statethis.setState 管理状态:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Clicked {this.state.count} times
      </button>
    );
  }
}

事件处理

绑定事件
React 事件使用驼峰命名法:

function handleClick() {
  console.log('Button clicked');
}

<button onClick={handleClick}>Click me</button>

传递参数
通过箭头函数或 bind 传递参数:

<button onClick={(e) => handleClick(id, e)}>Delete</button>

生命周期方法

类组件的生命周期
常用生命周期方法包括 componentDidMountcomponentWillUnmount

class Timer extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
  tick() {
    this.setState({ time: new Date() });
  }
}

Hook 替代方案
函数组件中使用 useEffect 替代生命周期:

import { useEffect } from 'react';

function Timer() {
  useEffect(() => {
    const timerID = setInterval(() => tick(), 1000);
    return () => clearInterval(timerID);
  }, []);
}

列表渲染

使用 map 渲染列表
通过 map 方法生成元素数组:

react.js如何编写

const numbers = [1, 2, 3];
const listItems = numbers.map((number) =>
  <li key={number}>{number}</li>
);

key 的重要性
key 帮助 React 识别列表项的变化:

const todoItems = todos.map((todo) =>
  <li key={todo.id}>{todo.text}</li>
);

表单处理

受控组件
表单元素的值由 React 状态控制:

function NameForm() {
  const [value, setValue] = useState('');
  const handleChange = (event) => setValue(event.target.value);
  return <input type="text" value={value} onChange={handleChange} />;
}

表单提交
阻止默认提交行为并处理数据:

function handleSubmit(event) {
  event.preventDefault();
  console.log('Submitted value:', inputValue);
}
<form onSubmit={handleSubmit}>...</form>

样式处理

内联样式
通过 JavaScript 对象定义样式:

const divStyle = { color: 'blue', fontSize: '20px' };
<div style={divStyle}>Styled text</div>

CSS 模块
使用 CSS 模块实现作用域样式:

import styles from './Button.module.css';
<button className={styles.error}>Error Button</button>

路由配置

安装 React Router
使用 react-router-dom 实现路由:

react.js如何编写

npm install react-router-dom

基本路由配置
定义路由和导航链接:

import { BrowserRouter, Route, Link } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Link to="/">Home</Link>
      <Route exact path="/" component={Home} />
    </BrowserRouter>
  );
}

数据获取

使用 fetch API
从服务器获取数据:

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => setData(data));
}, []);

异步函数
使用 async/await 处理异步请求:

async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  setData(data);
}

状态提升

共享状态
将子组件的状态提升到父组件:

function Parent() {
  const [value, setValue] = useState('');
  return <Child value={value} onChange={setValue} />;
}

function Child({ value, onChange }) {
  return <input value={value} onChange={(e) => onChange(e.target.value)} />;
}

上下文 API

创建上下文
通过 createContext 共享全局数据:

const ThemeContext = React.createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

使用上下文
通过 useContext Hook 访问上下文:

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div className={theme}>Theme</div>;
}

标签: reactjs
分享给朋友:

相关文章

react 如何引入jquery

react 如何引入jquery

引入 jQuery 到 React 项目 在 React 项目中引入 jQuery 可以通过多种方式实现,但需要注意 React 和 jQuery 操作 DOM 的方式可能冲突,因此建议仅在必要时使用…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment: npm install react-moment 或 yarn add react-moment 基本…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何diff

react如何diff

React Diff 算法原理 React 的 Diff 算法是 Virtual DOM 的核心部分,用于高效更新真实 DOM。其核心思想是通过对比新旧 Virtual DOM 树的差异,最小化 DO…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx c…

react 如何启动

react 如何启动

创建 React 项目 使用官方工具 create-react-app 快速初始化项目,需提前安装 Node.js(版本 ≥ 14.0.0)和 npm/yarn: npx create-react-…