当前位置:首页 > 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 方法生成元素数组:

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 实现路由:

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>;
}

react.js如何编写

标签: reactjs
分享给朋友:

相关文章

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment 包。确保项目中已安装 moment.js,因为 react-moment 依赖它。 npm install…

js 实现vue

js 实现vue

实现 Vue 的核心功能 在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路: 响应式系统 通过 Object.define…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableElem…

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…

react 如何执行

react 如何执行

安装 Node.js 和 npm React 开发需要 Node.js 环境,因为它提供了 npm(或 yarn)包管理工具。从 Node.js 官网 下载并安装最新 LTS 版本。安装完成后,在终端…