0x00 前言
文中工具皆可关注 皓月当空w 公众号 发送关键字 工具 获取
0x01 State
1.State修改
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {isHot:true}
}
render(){
return <h1>今天天气很炎热</h1>
}
}
2.状态读取
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {isHot:true}
}
render(){
return <h1>今天天气很{this.state.isHot ? '炎热':'凉爽'}</h1>
}
}
3.事件绑定
<script type="text/babel">
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {isHot:false}
}
render(){
return <h1 onClick={demo}>今天天气很{this.state.isHot ? '炎热':'凉爽'}</h1>
}
}
ReactDOM.render(<Weather/>,document.getElementById('test'))
function demo(){
alert("按钮被单击了")
}
</script>
4. 方法绑定
通过bind生成新的方法
<script type="text/babel">
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {isHot:false}
this.changeWeather = this.changeWeather.bind(this)
}
render(){
return <h1 onClick={this.changeWeather}>今天天气很{this.state.isHot ? '炎热':'凉爽'}</h1>
}
changeWeather(){
alert(this.state.isHot)
}
}
ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>
5.状态更新
状态修改必须得通过setState进行修改
<script type="text/babel">
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {isHot:false}
this.changeWeather = this.changeWeather.bind(this)
}
render(){
return <h1 onClick={this.changeWeather}>今天天气很{this.state.isHot ? '炎热':'凉爽'}</h1>
}
changeWeather(){
this.setState({isHot:!this.state.isHot})
}
}
ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>
6.精简模式
<script type="text/babel">
class Weather extends React.Component{
state = {isHot:false}
render(){
return <h1 onClick={this.changeWeather}>今天天气很{this.state.isHot ? '炎热':'凉爽'}</h1>
}
changeWeather=()=>{
this.setState({isHot:!this.state.isHot})
}
}
ReactDOM.render(<Weather/>,document.getElementById('test'))
</script>
other
欢迎大家关注我朋友的公众号 皓月当空w 分享漏洞情报以及各种学习资源,技能树,面试题等。
以上