高仿实现useState
程序员文章站
2022-06-28 18:01:24
html模拟 Document
...
html模拟
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<div id="root"></div>
<div id="box"></div>
<button id="heandlebtn">点击root</button>
<button id="handelebtn">点击box</button>
</div>
<script>
const root = document.getElementById('root');
const box = document.getElementById('box');
const heandlebtn = document.getElementById('heandlebtn');
const handelebtn = document.getElementById('handelebtn');
let hookStates = [];
let count = 0;
function useState(initialState) {
hookStates[count] = hookStates[count] || initialState;
// 利用闭包维护函数调用位置
let currentIndex = count;
function setState(newState) {
// 判断传入的state是否为函数,如果是把prevState传入
if (typeof newState === "function") {
// 重新复制给newState
newState = newState(hookStates[currentIndex]);
}
// 更新state
hookStates[currentIndex] = newState;
count = 0
// 触发视图更新
render();
}
// 返回数组形式,解构可写成任意变量
return [hookStates[count++], setState];
}
function render() {
const [count, setCount] = useState(0);
const [count1, setCount1] = useState(5)
heandlebtn.onclick = () => {
setCount(count => count + 5);
}
handelebtn.onclick = () => {
setCount1(count1+1)
}
root.innerHTML = count;
box.innerHTML = count1;
}
render()
</script>
</body>
</html>
react 自定义hooks模拟
import React from 'react';
import { render } from 'react-dom';
let mockState = [];
let count = 0;
const Component = <App />;
const Element = document.getElementById('root');
let useMockState = (params) => {
mockState[count] = mockState[count] || params;
let mockCurrent = count;
const setState = (newParams) => {
if(typeof newParams === 'function') {
newParams = newParams(mockState[mockCurrent])
}
mockState[mockCurrent] = newParams;
// setState修改之后,组件重新render,count标记回归起点
count = 0;
render(Component, Element)
}
return [mockState[count++], setState]
};
export {
useMockState
}
本文地址:https://blog.csdn.net/srTres/article/details/109643937
上一篇: Fireworks怎么制作立体感艺术字?