PHP前端开发

React 组件(基于类与函数式)

百变鹏仔 3天前 #JavaScript
文章标签 函数

react 组件是任何 react 应用程序的构建块。它们允许您将 ui 分成独立的、可重用的部分,可以单独管理和渲染。 react 组件有两种主要类型:功能组件和类组件。

功能组件
函数式组件更简单,并且被编写为 javascript 函数。它们将 props(输入数据)作为参数并返回 jsx,它描述了 ui 的外观。从 react 16.8 开始,函数式组件还可以使用 usestate 和 useeffect 等钩子来处理状态和副作用。

import react, { usestate } from 'react';const welcome = (props) =&gt; {  const [count, setcount] = usestate(0);  return (    <div>      <h1>hello, {props.name}!</h1>      <p>you've clicked {count} times</p>      <button onclick="{()"> setcount(count + 1)}&gt;click me</button>    </div>  );};export default welcome;

类组件
类组件是在 react 中编写组件的原始方式。它们扩展了 react.component 类,并且必须包含返回 jsx 的 render() 方法。类组件可以有自己的状态和生命周期方法,例如 componentdidmount、componentdidupdate 和 componentwillunmount。

import React, { Component } from 'react';class Welcome extends Component {  constructor(props) {    super(props);    this.state = { count: 0 };  }  handleClick = () =&gt; {    this.setState({ count: this.state.count + 1 });  }  render() {    return (      <div>        <h1>Hello, {this.props.name}!</h1>        <p>You've clicked {this.state.count} times</p>        <button onclick="{this.handleClick}">Click me</button>      </div>    );  }}export default Welcome;

关键概念:

钩子(用于功能组件):

react 鼓励创建小型、可重用的组件,这些组件可以组合起来形成更大的应用程序,保持代码库模块化且更易于维护。