当前位置:首页 > 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>
    );
  }
}

生命周期

类组件生命周期方法:

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() 渲染列表:

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:

react框架如何使用

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

分享给朋友:

相关文章

基于vue框架实现

基于vue框架实现

基于 Vue 框架实现功能需结合其核心特性(如组件化、响应式数据绑定)和生态工具(如 Vue Router、Pinia)。以下是关键实现步骤和代码示例: 项目初始化与基础配置 使用 Vite 或 V…

vue框架实现哪些功能

vue框架实现哪些功能

Vue框架的核心功能 响应式数据绑定 Vue通过数据劫持和发布-订阅模式实现双向绑定。当数据变化时,视图自动更新,无需手动操作DOM。例如: data() { return { message:…

vue评论框架的实现

vue评论框架的实现

实现Vue评论框架的基本结构 评论框架通常包含评论列表、发表评论表单和回复功能。使用Vue可以轻松构建响应式评论组件。 <template> <div class="comme…

vue实现页面骨框架

vue实现页面骨框架

Vue 实现页面骨架屏的方法 骨架屏(Skeleton Screen)是一种优化用户体验的技术,在页面数据加载前展示占位内容,避免空白或闪烁。以下是几种 Vue 实现骨架屏的方案: 使用 CSS 或…

vue框架实现日期显示

vue框架实现日期显示

实现日期显示的基本方法 在Vue中显示日期可以通过多种方式实现,以下是几种常见的方法: 使用JavaScript的Date对象 直接通过JavaScript的Date对象获取当前日期并显示: &l…

如何安装react框架

如何安装react框架

安装Node.js React框架的运行依赖Node.js环境,需先安装Node.js(包含npm包管理工具)。访问Node.js官网下载LTS版本,按提示完成安装。安装完成后,在终端运行以下命令验证…