当前位置:首页 > 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实现多级组件

Vue 多级组件实现方法 在 Vue 中实现多级组件通常涉及父子组件通信、动态组件或递归组件等技术。以下是几种常见实现方式: 父子组件嵌套 通过逐层嵌套组件实现多级结构,适用于固定层级场景:…

uniapp组件写法

uniapp组件写法

Uniapp 组件的基本写法 Uniapp 的组件写法与 Vue 类似,支持单文件组件(.vue 文件)。一个基本的组件通常包含三个部分:<template>、<script>…

vue实现折叠组件

vue实现折叠组件

实现折叠组件的基本思路 在Vue中实现折叠组件通常需要利用动态绑定和条件渲染。核心是通过控制一个布尔值状态来决定内容是否显示,并添加过渡动画提升用户体验。 基础实现方法 使用v-show或v-if控…

java如何写接口

java如何写接口

定义接口 在Java中,使用interface关键字定义接口。接口可以包含抽象方法、默认方法、静态方法和常量(隐式为public static final)。 public interface…

uniapp 分页组件

uniapp 分页组件

uniapp 分页组件实现方法 在uniapp中实现分页功能,可以通过自定义组件或使用第三方组件库完成。以下是几种常见实现方式: 自定义分页组件 创建一个名为uni-pagination的组件,模板…

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现 Vue组件是Vue.js的核心概念之一,允许将UI拆分为独立可复用的代码片段。组件的实现方式有多种,以下是常见的几种方法。 单文件组件(SFC) 单文件组件以.vue为后缀,将…