前端学习案例-React Hooks『useState』实现

第一步 安装环境

npm init -y

yarn add vite -D

第二步 演示usestate的功能

const {useState}=React
function App(){
    const [count,setCount]=useState(0)
    return (
        <div>
            <h1>{count}</h1>
            <button onClick={()=>setCount(count+1)}>+1</button>
        </div>
    )
}
ReactDOM.render(
    <App/>,
    document.querySelector("#app")
)

第三步 手动封装替代

const MyReact = (() => {
  let _state;
  function useState(initialState) {
    debugger
    _state = _state == undefined ? initialState : _state;
    return [_state, _setState];
  }
  const _setState = (newState) => {
    _state = newState;
    render();
  };
  return {
    useState,
  };
})();
function render() {
  ReactDOM.render(<App />, document.querySelector("#app"));
}
const { useState } = MyReact;
function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  );
}
ReactDOM.render(<App />, document.querySelector("#app"));

实现-1操作

const { useState } = React;
function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={()=>setCount(count=> count - 1)}>-1</button>
    </div>
  );
}
ReactDOM.render(<App />, document.querySelector("#app"));