const root = ReactDOM.createRoot(document.querySelector('#app'));
root.render(<App />)
const MyReact = (() => {
    let _state;

    function useState(initialState) {
        _state = _state === undefined ? initialState : _state
        const _setState = function (newState) {
            if(typeof newState==='function'){
                _state=newState(_state)
            }else{
                _state = newState
            }
           
            render()
           
        }
        return [_state, _setState]

    }
    function render() {
        root.render(<App />)
    }
    return{
        useState
    }

   
})()

const { useState } = MyReact

function App() {
    const [title, setTitle] = useState("this is a title")
    const [content, setContent] = useState("this is a content")
    return (
        <div>
            <h1>{title}</h1>
            <button onClick={() => setTitle("这是标题")}>set title</button>
            <p>{content}</p>
            <button onClick={() => setContent("这是内容")}>set content</button>
        </div>
    )
}

改变值得时候所有值都会变化

前端学习笔记202309学习笔记第九十一天-闭包28_前端