当前位置:首页 > 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 管理内部状态:

react如何使用组件

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

使用逻辑与运算符简化:

react如何使用组件

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 传递渲染逻辑的技术:

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中实现分页功能,通常需要父子组件之间的数据传递。以下是几种常见的传值方式: 使用props传递数据 父组件通过props向子组件传递当前页码和总页数等分页信息…

uniapp倒计时组件

uniapp倒计时组件

uniapp倒计时组件实现方法 使用内置组件实现 uniapp提供了<countdown>组件用于倒计时功能,支持自定义格式和样式。示例代码如下: <countdown :…

uniapp组件

uniapp组件

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

uniapp组件写法

uniapp组件写法

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

vue实现广告组件

vue实现广告组件

vue实现广告组件的方法 使用动态组件实现 在Vue中可以通过动态组件的方式加载广告组件,根据不同的条件展示不同的广告内容。动态组件使用<component :is="currentCompon…

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性来完成。以下是几种常见的实…