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) {
if (typeof newState === "function") {
newState = newState(hookStates[currentIndex]);
}
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;
count = 0;
render(Component, Element)
}
return [mockState[count++], setState]
};
export {
useMockState
}