当前位置:首页 > React

如何使用react组件

2026-02-12 04:10:25React

创建 React 组件

React 组件分为函数组件和类组件两种形式。函数组件是简单的 JavaScript 函数,类组件则继承自 React.Component

函数组件示例

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

类组件示例

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

使用 Props 传递数据

Props 是组件的输入参数,用于从父组件向子组件传递数据。

function App() {
  return <Greeting name="React" />;
}

使用 State 管理内部状态

State 用于存储组件的内部状态,类组件通过 this.statethis.setState 管理,函数组件使用 useState Hook。

类组件 State 示例

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

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

函数组件 State 示例

import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

生命周期方法(类组件)

类组件提供生命周期方法,如 componentDidMountcomponentDidUpdatecomponentWillUnmount

class LifecycleExample extends React.Component {
  componentDidMount() {
    console.log('Component mounted');
  }

  componentDidUpdate() {
    console.log('Component updated');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <div>Lifecycle Example</div>;
  }
}

使用 Hooks(函数组件)

Hooks 是函数组件的扩展功能,如 useStateuseEffectuseContext

useEffect 示例

import { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

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

  return <div>Seconds: {seconds}</div>;
}

组件组合与复用

通过组合多个组件构建复杂 UI,推荐使用 props 和 children 实现复用。

function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      <div className="content">{children}</div>
    </div>
  );
}

function App() {
  return (
    <Card title="Welcome">
      <p>This is the card content.</p>
    </Card>
  );
}

处理事件

React 事件使用驼峰命名(如 onClick),直接传递函数作为处理程序。

function ButtonClick() {
  const handleClick = () => {
    alert('Button clicked!');
  };

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

条件渲染

使用 JavaScript 条件语句(如 if 或三元运算符)控制组件渲染。

function Greeting({ isLoggedIn }) {
  return isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>;
}

列表渲染

使用 map 方法渲染动态列表,并为每个项添加唯一的 key

如何使用react组件

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

分享给朋友:

相关文章

vue实现下拉框组件

vue实现下拉框组件

Vue 下拉框组件实现 基础实现 创建基础下拉框组件,使用v-model实现双向数据绑定: <template> <div class="dropdown"> &…

uniapp组件

uniapp组件

uniapp组件基础概念 uniapp的组件系统基于Vue.js,支持跨平台开发(H5、小程序、App等)。组件分为内置基础组件(如<view>、<button>)和自定义组件…

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

实现拖拽组件嵌套的核心思路 Vue中实现拖拽组件嵌套需要结合拖拽库(如vuedraggable)和组件递归渲染。核心在于动态管理嵌套数据结构,并通过事件传递实现层级更新。 安装必要依赖 推荐使用vu…

如何设计react组件

如何设计react组件

设计 React 组件的核心原则 React 组件的设计需要遵循高内聚、低耦合的原则,确保组件功能独立且易于维护。组件的设计可以分为展示组件和容器组件两类,展示组件负责 UI 渲染,容器组件负责逻辑处…

如何使用ink react

如何使用ink react

安装 Ink 和 React 在项目目录下运行以下命令安装 Ink 和 React 的依赖: npm install ink react 创建基础组件 创建一个简单的 Ink 组件,例如 Hello…

vue table组件实现

vue table组件实现

Vue 表格组件实现方案 基础表格实现 使用<table>标签结合v-for指令渲染数据是最简单的实现方式: <template> <table> &…