1-7 解决类中方法的this指向问题

React依赖包我已上传地址如下:https://download.youkuaiyun.com/download/weixin_39162041/86264167

        class Wather extends React.Component{
            constructor(props){
                super(props)
                this.state = {isHot:true}
                //解决demo中this指向问题
                //从原型链上查找到demo方法,并且通过bind改变this的指向为当前类的实例对象,并返回一个新的函数赋值给this.demo解决this指向问题
                this.demo = this.demo.bind(this)
            }
            render(){
                return <h1 onClick={this.demo}>今天天气很{this.state.isHot ?'炎热':'凉爽'}</h1>
            }
            demo(){
                //demo放在那里?---demo原型对象上,供实例使用
                //由于demo是作为onClick的回调所以不是通过实例调用,是直接调用。
                //类中的方法默认开启了局部的严格模式,所以demo中的this为undefined。
                console.log('此处修改isHot的值');
            }
        }
        ReactDOM.render(<Wather/>,document.getElementById('test'))

简写类式组件

	<script type="text/babel" > /* 此处一定要写babel */
        class Wather extends React.Component{
            state = {isHot:true}
            render(){
                return <h1 onClick={this.demo}>今天天气很{this.state.isHot ?'炎热':'凉爽'}</h1>
            }
            demo = ()=>{
                const  isHot = this.state.isHot
                this.setState({isHot:!isHot})
            }
        }
        ReactDOM.render(<Wather/>,document.getElementById('test'))

	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

画不完的饼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值