当前位置:首页 > 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
分享给朋友:

相关文章

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Pa…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

react 如何运行

react 如何运行

运行 React 项目的步骤 安装 Node.js 确保系统已安装 Node.js(建议版本 16+),可通过官网下载并安装。安装后验证版本: node -v npm -v 创建 React 项目…

如何提高react

如何提高react

优化性能 使用React.memo对组件进行记忆化处理,避免不必要的重新渲染。对于类组件,可以使用PureComponent来达到类似效果。 利用useMemo缓存计算结果,避免重复计算。对于函数…

如何关闭react

如何关闭react

关闭React应用的步骤 在开发或运行React应用时,可能需要关闭正在运行的开发服务器或停止应用。以下是几种常见情况的处理方法: 停止开发服务器 如果正在使用npm start或yarn sta…

react 如何精通

react 如何精通

掌握核心概念 深入理解React的基础概念,包括组件(函数组件与类组件)、状态(useState)、生命周期(useEffect)、Props传递、虚拟DOM与Diff算法。通过官方文档或《React…