当前位置:首页 > React

react如何使用组件

2026-02-12 07:49:12React

使用 React 组件的基本方法

React 组件是构建用户界面的核心单元,分为函数组件和类组件两种形式。以下是具体使用方法:

创建函数组件

函数组件是最简单的组件形式,通过 JavaScript 函数定义:

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

箭头函数写法同样适用:

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

创建类组件

类组件通过 ES6 的 class 语法定义,需继承 React.Component

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

组件嵌套使用

组件可以像 HTML 标签一样嵌套使用:

function App() {
  return (
    <div>
      <Welcome name="Alice" />
      <Welcome name="Bob" />
    </div>
  );
}

传递 Props

通过属性(props)向组件传递数据:

<Welcome name="Alice" age={25} />

在组件内部通过 props 对象访问:

function Welcome(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}

使用状态(State)

类组件中使用 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>
    );
  }
}

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

import { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

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

生命周期方法(类组件)

类组件可以通过生命周期方法处理不同阶段的逻辑:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({ date: new Date() });
  }

  render() {
    return <div>Current time: {this.state.date.toLocaleTimeString()}</div>;
  }
}

处理事件

React 事件处理采用驼峰命名法:

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

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

条件渲染

根据条件决定渲染内容:

function Greeting(props) {
  if (props.isLoggedIn) {
    return <h1>Welcome back!</h1>;
  }
  return <h1>Please sign in.</h1>;
}

使用逻辑与运算符简化:

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      {unreadMessages.length > 0 && (
        <h2>You have {unreadMessages.length} unread messages.</h2>
      )}
    </div>
  );
}

列表渲染

使用 map() 方法渲染列表:

function NumberList(props) {
  const numbers = props.numbers;
  return (
    <ul>
      {numbers.map((number) => (
        <li key={number.toString()}>{number}</li>
      ))}
    </ul>
  );
}

组合 vs 继承

React 推荐使用组合而非继承来实现组件复用:

function Dialog(props) {
  return (
    <div className="dialog">
      <div className="dialog-header">{props.header}</div>
      <div className="dialog-content">{props.children}</div>
    </div>
  );
}

function WelcomeDialog() {
  return (
    <Dialog header="Welcome">
      <p>Thank you for visiting our spacecraft!</p>
    </Dialog>
  );
}

使用 Context 跨组件传递数据

对于深层嵌套组件,使用 Context 避免逐层传递 props:

const ThemeContext = React.createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Themed Button</button>;
}

高阶组件(HOC)

高阶组件是复用组件逻辑的高级技术:

function withSubscription(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = { data: [] };
    }

    componentDidMount() {
      // 获取数据逻辑
    }

    render() {
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };
}

const EnhancedComponent = withSubscription(OriginalComponent);

渲染属性(Render Props)

通过 prop 传递渲染逻辑的技术:

react如何使用组件

class Mouse extends React.Component {
  constructor(props) {
    super(props);
    this.state = { x: 0, y: 0 };
  }

  handleMouseMove = (event) => {
    this.setState({
      x: event.clientX,
      y: event.clientY
    });
  };

  render() {
    return (
      <div onMouseMove={this.handleMouseMove}>
        {this.props.render(this.state)}
      </div>
    );
  }
}

function App() {
  return (
    <Mouse
      render={({ x, y }) => (
        <h1>
          Mouse position: {x}, {y}
        </h1>
      )}
    />
  );
}

分享给朋友:

相关文章

vue怎么实现组件缓存

vue怎么实现组件缓存

vue实现组件缓存的方法 在Vue中实现组件缓存可以通过内置的<keep-alive>组件完成,该组件能够缓存不活动的组件实例,避免重复渲染。 使用<keep-alive>基…

uniapp组件

uniapp组件

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

如何使用ink react

如何使用ink react

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

react如何使用redux

react如何使用redux

使用 Redux 在 React 中的应用 Redux 是一个状态管理库,通常与 React 结合使用以管理全局状态。以下是具体实现步骤: 安装依赖 确保项目中已安装 redux 和 react-r…

如何判断react组件

如何判断react组件

判断 React 组件的依据 React 组件的判断通常基于其定义方式、功能特性和代码结构。以下是几种常见的判断方法: 函数组件与类组件 函数组件是通过 JavaScript 函数定义的,接收 pr…

vue实现父子组件

vue实现父子组件

Vue 父子组件通信实现方式 1. 父组件向子组件传递数据(Props) 父组件通过 props 向子组件传递数据,子组件通过 props 接收数据。 父组件模板: <template>…