当前位置:首页 > 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 复用状态逻辑:

react如何写组件

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 组件的主要写法,根据具体需求选择合适的实现方式。

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

相关文章

vue实现组件跟随

vue实现组件跟随

实现组件跟随的常见方法 使用CSS定位 通过CSS的position: fixed或position: absolute属性实现组件跟随。需要结合JavaScript计算目标元素的位置。 &…

vue table组件实现

vue table组件实现

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

vue组件实现tab

vue组件实现tab

Vue 组件实现 Tab 切换 基础实现方案 模板结构 使用 v-for 渲染标签页标题,通过 v-show 或 v-if 控制内容显示: <template> <div cl…

vue实现组件市场

vue实现组件市场

Vue 组件市场的实现方法 组件市场的基本架构 Vue 组件市场的核心是构建一个可展示、下载和管理组件的平台。需要设计前端展示界面、后端数据存储和组件打包发布流程。采用 Vue 3 + TypeScr…

vue组件怎么实现

vue组件怎么实现

Vue 组件的实现方法 Vue 组件是 Vue.js 的核心特性之一,用于封装可复用的代码。组件的实现方式包括全局注册和局部注册,同时支持单文件组件(SFC)和模板语法。 全局注册组件 通过 Vue…

vue父子组件实现

vue父子组件实现

Vue 父子组件通信实现 Vue 父子组件通信主要通过 props 和 events 实现,父组件向子组件传递数据使用 props,子组件向父组件传递数据使用自定义事件。 父组件向子组件传递数据 父…