React-函数组件(Functional Components)

例子

使用类组件

import React from 'react'

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.sayHi = this.sayHi.bind(this);
  }

  sayHi() {
    alert(`Hi ${this.props.name}`);
  }

  render() {
    return (
      

Hello, {this.props.name}

) } }

将它改成函数组件

function Welcome = (props) => {
  const sayHi = () => {
    alert(`Hi ${props.name}`);
  }

  return (
    

Hello, {props.name}

) }

与类组件的区别

  1. 没有this
  2. 无法被实例化
  3. 没有状态(state),所以函数组件也叫无状态组件(Stateless Components)
  4. 没有生命周期

所以函数特别适合用来写只接收props渲染DOM,不考虑其他逻辑的展示型组件(Presentational Components)

你可能感兴趣的:(React,JavaScript,前端)