当前位置:首页 > React

react如何写组件

2026-02-26 19:40:17React

React 组件的写法

React 组件可以通过函数组件和类组件两种方式编写。以下是常见的写法:

函数组件

函数组件是使用 JavaScript 函数定义的组件,适用于简单的 UI 渲染。

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

箭头函数写法:

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

类组件

类组件继承 React.Component,适用于需要状态管理和生命周期方法的场景。

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

组件状态管理

函数组件使用 useState Hook 管理状态:

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

类组件通过 this.statethis.setState 管理状态:

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

组件生命周期

类组件可以通过生命周期方法(如 componentDidMountcomponentDidUpdate)处理副作用:

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

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

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

函数组件使用 useEffect Hook 替代生命周期:

import { useEffect } from 'react';

function Example() {
  useEffect(() => {
    console.log('Component mounted or updated');
    return () => {
      console.log('Component will unmount');
    };
  }, []);

  return <div>Effect Example</div>;
}

组件通信

父组件通过 props 向子组件传递数据:

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

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

子组件通过回调函数向父组件传递数据:

function Parent() {
  const handleChildClick = (data) => {
    console.log('Data from child:', data);
  };

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

function Child({ onClick }) {
  return <button onClick={() => onClick('Child data')}>Click Me</button>;
}

组件样式

内联样式:

function StyledComponent() {
  return <div style={{ color: 'red', fontSize: '20px' }}>Styled Text</div>;
}

CSS 模块:

import styles from './Component.module.css';

function StyledComponent() {
  return <div className={styles.text}>Styled Text</div>;
}

组件复用

通过高阶组件(HOC)复用逻辑:

function withLogger(WrappedComponent) {
  return function(props) {
    console.log('Rendered:', WrappedComponent.name);
    return <WrappedComponent {...props} />;
  };
}

const EnhancedComponent = withLogger(MyComponent);

通过自定义 Hook 复用状态逻辑:

function useCounter(initialValue) {
  const [count, setCount] = useState(initialValue);
  const increment = () => setCount(count + 1);
  return { count, increment };
}

function CounterA() {
  const { count, increment } = useCounter(0);
  return <button onClick={increment}>Count: {count}</button>;
}

以上是 React 组件的主要写法,根据具体需求选择合适的实现方式。

react如何写组件

标签: 组件如何写
分享给朋友:

相关文章

vue实现组件拖放

vue实现组件拖放

Vue 实现组件拖放的方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

vue实现水印组件

vue实现水印组件

Vue 水印组件实现 基础水印组件实现 创建一个基础水印组件,通过 props 接收文本、颜色、大小等参数: <template> <div class="watermark-…

vue实现穿梭框树组件

vue实现穿梭框树组件

Vue 穿梭框树组件实现 穿梭框树组件通常结合了树形结构和穿梭框功能,允许用户在左右两栏之间移动树节点数据。以下是基于 Vue 的实现方案: 核心功能设计 数据结构 树形数据通常采用嵌套结构,例如:…

java如何写一个接口

java如何写一个接口

在Java中定义接口 接口在Java中是一种抽象类型,用于定义一组方法规范,供类实现。接口通过interface关键字声明,可以包含抽象方法、默认方法、静态方法和常量。 public interfa…

vue抽屉组件实现

vue抽屉组件实现

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

vue组件实现vmodel

vue组件实现vmodel

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