常用的生命週期函式
阿新 • • 發佈:2021-08-10
importReact,{Component}from'react'
classCpnextendsComponent{
render(){
return(
<div>我是Cpn元件</div>
)
}
componentWillUnmount(){ console.log('呼叫了cpn的componentWillUnmount方法') } }
exportdefaultclassAppextendsComponent{
constructor(){ super(); this.state={ counter:0, isShow:true }
console.log('執行了constructor方法'); } componentDidMount(){ console.log('執行了元件componentDidMount方法'); }
componentDidUpdate(){ console.log('執行了元件componentDidUpdate方法'); }
render(){ console.log('執行了元件render方法'); return( <div> <h2>App元件</h2> <h2>當前計數:{this.state.counter}</h2> <buttononClick={e=>this.increment()}>+1</button> <hr/> <buttononClick={e=>this.changeCpnShow()}>切換</button> {this.state.isShow&&<Cpn/>}
</div> ) }
increment(){ this.setState({ counter:this.state.counter+1 }) }
changeCpnShow(){ this.setState({ isShow:!this.state.isShow }) }
} 我是Eric,手機號是13522679763
componentWillUnmount(){ console.log('呼叫了cpn的componentWillUnmount方法') } }
exportdefaultclassAppextendsComponent{
constructor(){ super(); this.state={ counter:0, isShow:true }
console.log('執行了constructor方法'); } componentDidMount(){ console.log('執行了元件componentDidMount方法'); }
componentDidUpdate(){ console.log('執行了元件componentDidUpdate方法'); }
render(){ console.log('執行了元件render方法'); return( <div> <h2>App元件</h2> <h2>當前計數:{this.state.counter}</h2> <buttononClick={e=>this.increment()}>+1</button> <hr/> <buttononClick={e=>this.changeCpnShow()}>切換</button> {this.state.isShow&&<Cpn/>}
</div> ) }
increment(){ this.setState({ counter:this.state.counter+1 }) }
changeCpnShow(){ this.setState({ isShow:!this.state.isShow }) }
} 我是Eric,手機號是13522679763