当前位置:首页 > 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 组件是 Vue.js 的核心特性之一,允许开发者将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种常见方式: 单文件组件(SFC) 单文件组件是 Vue 中…

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gree…

react如何使用路由

react如何使用路由

使用 React Router 的基本方法 React Router 是 React 应用中实现路由功能的核心库。以下是基本使用方法: 安装 React Router 依赖包: npm insta…

react如何使用函数

react如何使用函数

使用函数组件的基本语法 在React中,函数组件是通过JavaScript函数定义的组件。函数接收props作为参数,并返回React元素。 function Welcome(props) {…

react thunk 如何使用

react thunk 如何使用

使用 React Thunk 的基本步骤 安装 Redux 和 Redux Thunk 作为依赖项: npm install redux redux-thunk 在 Redux store 配置中应…

vue实现组件切换

vue实现组件切换

Vue 组件切换的实现方法 在 Vue 中实现组件切换有多种方式,以下是几种常见的方法: 动态组件 使用 Vue 内置的 <component> 元素和 is 属性可以动态切换组件:…