1. 函数组件(Functional Components)

函数组件是一个JavaScript函数,它接收一个props对象作为参数,并返回一个React元素(通常是一个虚拟DOM节点)。函数组件通常是无状态的,它们只依赖于输入的props,没有内部状态,并且不执行副作用。函数组件通常用于渲染静态内容,例如纯展示组件。

示例:

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}
  1. 类组件(Class Components)

类组件是ES6类,它扩展了React.Component类,它可以包含内部状态(通过this.state访问)和生命周期方法。类组件通常用于管理动态数据,例如处理用户输入、更新组件状态等。

示例:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleClick() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.handleClick()}>Click me</button>
      </div>
    );
  }
}
react两种组件

原文地址: http://www.cveoy.top/t/topic/KY2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录