当前位置:首页 > React

react框架如何使用

2026-02-12 07:46:04React

安装 React

使用 Create React App 快速搭建项目:

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

组件基础

函数组件示例:

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

类组件示例:

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

状态管理

函数组件使用 Hook:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

类组件状态管理:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

生命周期

类组件生命周期方法:

react框架如何使用

class Clock extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      time: new Date().toLocaleTimeString()
    });
  }

  render() {
    return (
      <div>
        <h1>Current Time:</h1>
        <h2>{this.state.time}</h2>
      </div>
    );
  }
}

函数组件使用 useEffect:

import { useState, useEffect } from 'react';

function Clock() {
  const [time, setTime] = useState(new Date().toLocaleTimeString());

  useEffect(() => {
    const timerID = setInterval(() => {
      setTime(new Date().toLocaleTimeString());
    }, 1000);

    return () => clearInterval(timerID);
  }, []);

  return (
    <div>
      <h1>Current Time:</h1>
      <h2>{time}</h2>
    </div>
  );
}

事件处理

事件绑定示例:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

列表渲染

使用 map() 渲染列表:

react框架如何使用

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>
      {number}
    </li>
  );

  return <ul>{listItems}</ul>;
}

表单处理

受控组件示例:

function NameForm() {
  const [value, setValue] = useState('');

  function handleChange(event) {
    setValue(event.target.value);
  }

  function handleSubmit(event) {
    alert('A name was submitted: ' + value);
    event.preventDefault();
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

组件通信

父传子:

function Parent() {
  const message = "Hello from parent";
  return <Child message={message} />;
}

function Child(props) {
  return <h1>{props.message}</h1>;
}

子传父:

function Parent() {
  function handleChildClick(data) {
    console.log("Data from child:", data);
  }

  return <Child onClick={handleChildClick} />;
}

function Child(props) {
  function handleClick() {
    props.onClick("Data from child");
  }

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

使用 Context

创建和使用 Context:

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

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

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button theme={theme}>I am styled by theme!</button>;
}

分享给朋友:

相关文章

java如何使用

java如何使用

Java 基本使用方法 Java 是一种广泛使用的编程语言,适用于开发各种类型的应用程序。以下是 Java 的基本使用方法,包括环境配置、语法基础和常用操作。 安装 Java 开发环境 下载并安装…

react如何使用路由

react如何使用路由

使用 React Router 的基本方法 React Router 是 React 应用中实现路由功能的核心库。以下是基本使用方法: 安装 React Router 依赖包: npm insta…

jquery框架

jquery框架

jQuery框架简介 jQuery是一个快速、简洁的JavaScript库,简化了HTML文档遍历、事件处理、动画设计和Ajax交互。其核心特点是“写得更少,做得更多”,通过封装常见任务,降低跨浏览器…

如何使用 react native

如何使用 react native

安装开发环境 确保已安装 Node.js(建议使用 LTS 版本)。通过以下命令安装 React Native 命令行工具: npm install -g expo-cli 或使用 Yarn: y…

react如何使用函数

react如何使用函数

使用函数组件的基本语法 在React中,函数组件是通过JavaScript函数定义的组件。函数接收props作为参数,并返回React元素。 function Welcome(props) {…

如何搭建react框架

如何搭建react框架

安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网下载安装包或使用版本管理工具(如 nvm)。安装完成后,运行以下命令验证版本: node -v npm…