《React-Hooks 介绍》

React v16.7-alpha 版本,推出了一个新的 API 叫做 React-Hooks,它的主要功能是让 function component 可以像 class component 那样,可以处理 state, life-cycle, effect, context 等特性。

相比 class component,react-hooks 代码写起来更加简洁,并且可复用性更高。

什么是Hooks

Hooks是一个新特性提议,它可以让你在不用class的的情况下依然能够使用state和其他的 React 特性

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useState这个新方法是我们学到的第一个‘Hook’,如果你对Hooks还是没有太多感觉,不要担心,上面的例子只是小试牛刀!
接下来我们会解释为什么要在React中加入Hooks以及Hooks是如何帮你写一个非常棒的应用程序的。


一眼看完Hooks

Hooksbackwards-compatible(向下兼容)的,这一节可以让熟悉react的开发者快速预览一下啊Hooks

State Hook

下面这个例子渲染了一个计数器,当你点击这个按钮的时候数值会增加

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

声明更多的state变量

在一个component中可以多次使用State Hook

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

Effect Hook

下面这个例子在React更新DOM之后设置了文档标题

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

声明更多的state变量

在一个component中可以多次使用State Hook

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值