state属性

state 是组件自身的一个状态,组件内部自己的数据。

组件的加载流程(组件的生命周期函数)

首先 执行组件的构造器 constructor() 处理组件内部的状态

其次 执行 render() 得到一个虚拟DOM

最后 执行 componentDIdMount() 插入我们的真实DOM

生命周期图谱

类组件

<div id="app"></div>
    <script type="text/babel">
       //state
        class App extends React.Component{
            constructor(){
                super();
                //添加state状态
                this.state={
                    name:'小明'
                }
            }
            render (){
                return <div>
                    <h2>{this.state.name}</h2>
                    </div>
            }
        }
        ReactDOM.render(<App></App>,document.getElementById("app"))
    </script>

 

 

函数组件

函数组件不能直接添加state属性 使用后面的 Hooks 知识点。

 

state的注意:

  • state 是组件内部的数据状态

  • 读取state状态 直接使用 this.state

  • 更改state 需要使用 this.setSate()

    • this.setSate() 它是异步的

更改state

<div id="app"></div>
    <script type="text/babel">
       //state
        class App extends React.Component{            
            constructor(){
                super();
                //添加state状态
                this.state={
                    name:'小明'
                }
                //事件函数中绑定this
                this.click=this.click.bind(this)
            }
            click(){
                this.setState({
                    name:'小红'
                })
            }
            render (){
                console.log(this)
                return <div>
                    <h2>{this.state.name}</h2>
                    <button onClick={this.click}>修改state</button>
                    </div>
            }
        }
        ReactDOM.render(<App></App>,document.getElementById("app"))
    </script>

 

posted @ 2021-11-16 09:46  keyeking  阅读(84)  评论(0编辑  收藏  举报