react 中的 function Component

因为hooks的出现 解决了函数式 组件没有生命周期的一个痛点 同时也有一些新的坑等待我们

遇到的第一个坑就在配置了react-hot-loader的情况下无法使用hoosk原因是react-hot-loader的那个babel插件的问题 可能在解析某些语法上做了特殊的处理

class Component 和 function Component 的区别

为什么要了解 Function 写法的组件呢?因为它正在变得越来越重要。
那么 React 中 Function Component 与 Class Component 有何不同?

Capture props (props 的捕获)

对比下面两段代码。

class Component
import React from 'react';

class ProfilePage extends React.Component {
   
  showMessage = () => {
   
    alert('Followed ' + this.props.user);
  };

  handleClick = () => {
   
    setTimeout(this.showMessage, 3000);
  };

  render() {
   
    return <button onClick={
    this.handleClick }>Follow</button>;
  }
}

export default ProfilePage;

function Component

import React from 'react';

function ProfilePage(props) {
   
  const showMessage = () => {
   
    alert('Followed ' + props.user);
  };

  const handleClick = () => {
   
    setTimeout(showMessage, 3000);
  };

  return (
    <button onClick={
    handleClick }>Follow</button>
  );
}

export default ProfilePage;

这两个组件都描述了同一个逻辑:点击按钮 3 秒后 alert 父级传入的用户名。

父级组件代码

import React from "react";
import ReactDOM from "react-dom";

import ProfilePageFunction from './ProfilePageFunction';
import ProfilePageClass from './ProfilePageClass';

class App extends React.Component{
   

  state 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值