REACT学习--初始化state和改变自定义方法this指向问题

使用constructor来初始化state和手动改变自定义方法的this指向          
class Study extends React.Component{
            constructor(props){
                super(props)
                this.state = {isS:false};
                this.changeStatus = this.changeStatus.bind(this)    
               
            }
            state = {isS:false};
            render(h) {
                const {isS} = this.state
                return <h1 onClick={this.changeStatus}>{isS ? "学习" : "不学"}REACT</h1>
            }
            changeStatus (){
                const {isS} = this.state
                this.setState({isS:!isS})
            }
        }
        ReactDOM.render(<Study/>,document.getElementById("test"))

  2.使用赋值操作Class会默认添加类的自定义属性,箭头函数指向当前上下文 所以this会指向Study的实例

 class Study extends React.Compone
           state = {isS:false};
            render(h) {
             const {isS} = this.state
             return <h1 onClick={this.changeStatus}>{isS ? "学习" : "不学"}REACT</h1>
           }
            changeStatus =()=>{
                const {isS} = this.state
                this.setState({isS:!isS})
            }
        }
        ReactDOM.render(<Study/>,document.getElementById("test"))
    

 

posted @ 2021-01-13 18:00  不秃头的代码狗  阅读(156)  评论(0)    收藏  举报