1:简化state
不想用bind改变change的this指向,造成change指向的原因是引用了bind 开启了严格模式,
而箭头函数的this指向父级,所以我就可以使用箭头函数代替普通change方法,然后就不用在初始化那写改变了
2:在onclick的身上不可以用方法然后加()这样这个方法就会一直执行这是因为这个页面一上来这个render 就会自动执行然后就相当于change发生改变 state就会发生改变, 都会一起进行执行进入死循环导致内存泄漏
3:箭头函数普通函数的方法如何调用以及this指向问题
<script type="text/babel">
class Weather extends React.Component {
constructor() {
super()
this.state = {
isHot: true,
wind: "微风",
date: new Date().toLocaleTimeString()
}
this.go = this.go.bind(this)
}
render() {
console.log("Render");
// 只要渲染 就会调用
let { isHot, wind } = this.state
return (
//不要在 onclcik中 直接调用其他方法(this.setState({ isHot: !isHot }))
<div>
<h1>{this.state.date}</h1>
<h2 onClick={this.change}>
今天天气是{isHot ? "炎热的" : "凉爽的"},{wind}
</h2>
<button onClick={this.go}>按钮(go)</button>
<button onClick={function () {
// onclick里面再来一个function 这里的this也是underfined
console.log(this);
//所以再这里this.go1()也执行不了了
this.go1()
}}>按钮(go1)</button>
<button onClick={this.go.bind(this)}>按钮(go2)</button>
<button onClick={this.go1}>按钮(go3)</button>
</div>
)
}
// 箭头函数的this指向 依赖的是window
change = () => {
console.log("Change", this);
let isHot = this.state.isHot
this.setState({ isHot: !isHot })
}
go() {
//普通函数需要在严格模式下需要改变一个bind 然后再render里面用这个方法
console.log("go", this);
this.setState({
isHot: true,
wind: "微风",
date: new Date().toLocaleTimeString()
})
}
//箭头函数
go1 = () => {
console.log("go1", this);
this.setState({
isHot: true,
wind: "微风",
date: new Date().toLocaleTimeString()
})
}
}
ReactDOM.render(<Weather />, document.querySelector("#app"))
</script>
4:react中的props
创建一个类 把数据类型解构赋给props 这样这个类里面就会有props 然后当你的数据通过外部传进来的值props里面的值也会进行更改,从而进行页面显示。类型多的时候可以用...进行拷贝来显示。
5:props的限制(规定)
6:函数组件也可以使用props
7:重点---函数抽取组件
8:重点类抽取组件
9:ref重点内容