React Hooks
Hooks是一个新的react特性提案,适用于函数式组件(视图组件),如果需要外部react特性(比如状态管理、生命周期),就用钩子把外部特性“钩”进来,典型标志是函数名字都是以use开头。
let [count, setCount] = useState(100);
useEffect(()=>{
return ()=>{
}
}, [])
const [state, dispatch] = useReducer(reducer, initialState, init);
封装hooks获取窗口大小
// useWinSize
import React, {
useState ,useEffect ,useCallback } from 'react';
export default function useWinSize(){
const [ size , setSize] = useState({
width:document.documentElement.clientWidth,
height:document.documentElement.clientHeight
})
const onResize = useCallback(()=>{
setSize({
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
})
},[])
useEffect(()=>{
window.addEventListener('resize',onResize)
return ()=>{
window.removeEventListener('resize',onResize)
}
},[])
return size;
}
// demo.js
import useWinSize from './useWinSize'
export default function(){
const size = useWinSize()
return (
<div>页面Size:{
size.width}x{
size.height}</div>
)
}
延迟设置值
import React, {
useState, useRef, useEffect} from 'react'
export const useDelayState = (initialState)=>{
const [state, setState] = useState(initialState);
const ref = useRef();
const delaySetState = (value, delay)=>{
ref.current = setTimeout(()=>{
setState(value)
}, delay)
}
useEffect(()=>{
return ()=>{
clearTimeout(ref.current)
}
}, [])
return [state, delaySetState, setState]
}
GeoLocation获取地理定位
import {
useEffect, useState } from 'react';
const useGeolocation = options => {
const [state, setState] = useState({
loading: true,
accuracy: null,
altitude: null,
altitudeAccuracy: null,
heading: null,
latitude: null,
longitude: null,
speed: null,
timestamp: Date.now(),
});
let mounted = true;
let watchId: any;
const onEvent = event => {
if (mounted) {
setState({
loading: false,
accuracy: event.coords.accuracy,
altitude: event.coords.altitude,
altitudeAccuracy: event.coords.altitudeAccuracy,
heading: event.coords.heading,
latitude: event.coords.latitude,
longitude: event.coords.longitude,
speed: event.coords.speed,
timestamp: event.timestamp,
});
}
};
const onEventError = (error) =>
mounted && setState(oldState => ({
...oldState, loading: false, error }));
useEffect(() => {
navigator.geolocation.getCurrentPosition(onEvent, onEventError, options);
watchId = navigator.geolocation.watchPosition(onEvent, onEventError, options);
return () => {
mounted = false;
navigator.geolocation.clearWatch(watchId);
};
}, []);
return state;
};
export default useGeolocation;
去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片
.
// An highlighted block
var foo = 'bar';