当前位置:首页 > 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 示例

如何使用react组件

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 示例

如何使用react组件

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

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

分享给朋友:

相关文章

如何使用 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) {…

vue抽屉组件实现

vue抽屉组件实现

Vue 抽屉组件实现 使用 Element UI 实现 Element UI 提供了现成的抽屉组件 el-drawer,可以快速实现抽屉效果。 安装 Element UI: npm install…

vue组件实现vmodel

vue组件实现vmodel

Vue 组件实现 v-model 在 Vue 中,v-model 是双向数据绑定的语法糖,默认情况下绑定 value 属性并监听 input 事件。在自定义组件中实现 v-model 需要正确配置 p…

vue实现分页组件

vue实现分页组件

Vue 分页组件实现 基础分页组件结构 创建一个名为 Pagination.vue 的文件,包含以下基础模板和逻辑: <template> <div class="pa…

vue实现弹窗组件

vue实现弹窗组件

实现弹窗组件的基本结构 在Vue中创建一个弹窗组件通常需要三个核心部分:组件模板、样式和逻辑控制。弹窗组件应具备打开、关闭功能,并支持内容插槽或属性传入。 <template> &l…