State
state
changeWeather 放在哪里? Weather 的原型对象上 供实例使用
由于 changeWeather 是作为 onClick 的回调 所以不是通过实例调用的 是直接调用!!!
console.log(this); // 实际指向的是 Windows 因为 类中的方法默认开启了局部的严格模式 所以 changeWeather 中的 this 为 undefined
// 1.创建函数式组件
class Weather extends React.Component {
constructor(props) {
// 构造器调用几次 constructor 1次
console.log('constructor');
super(props)
// 初始化状态
this.state = {
isHot: true,
wind: '微风'
}
// 改变 changeWeather 的this指向 稍微有点绕 多看看
this.changeWeather = this.changeWeather.bind(this)
}
render() {
// render 调用几次 1+n n是状态更新的次数
console.log('render');
// console.log('render中的this', this);
const { isHot, wind } = this.state
return <h2 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h2>
}
changeWeather() {
// changeWeather 放在哪里? Weather 的原型对象上 供实例使用
// 由于 changeWeather 是作为 onClick 的回调 所以不是通过实例调用的 是直接调用!!!
// console.log(this); // 实际指向的是 Windows 因为 类中的方法默认开启了局部的严格模式 所以 changeWeather 中的 this 为 undefined
const { isHot } = this.state
// 严重注意 状态必须通过setState进行更新 且更新是一种合并 不是替换
this.setState({
isHot: !isHot
})
}
}
// 2.渲染组件到页面
ReactDOM.render(<Weather />, document.querySelector('#test'))
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
study() {
console.log(this);
}
}
const p1 = new Person('雨神', 19)
console.log(p1);
p1.study()
let x = p1.study
x()
state 的简写方式
class Weather extends React.Component {
state = {
isHot: true,
wind: '微风'
}
render() {
const { isHot, wind } = this.state
return <h2 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h2>
}
// 自定义方法 要写赋值语句的形式 加箭头函数
changeWeather= () => {
const { isHot } = this.state
this.setState({
isHot: !isHot
})
}
}
准确区分什么是简单组件与复杂组件
- 简单组件无state
- 复杂组件有state
初始化state
在组件类的构造器中修改
先给构造器传参数props,这个参数是React自动给我们传的。
调用super()
初始化state
这里的this指的是组件的实例对象
React中的点击事件
- 在JSX语法的行内添加点击事件
- onClick中的C要大写
- 使用{}包裹函数,函数后面不要加上()
<h2 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h2>
changeWeather() {
// console.log(this); // 其实是window 严格模式下是 undefined
const { isHot } = this.state
this.setState({
isHot: !isHot
})
}
类中自定义方法的this指向
上面点击事件指的是系统点击的(windows) 由于 changeWeather 是作为onClick的回调 不是类的实例对象 因为babel开启了严格模式 本身指向的其实是window 严格模式下是 undefined
bind 方法不仅仅修改了this指向,同时将修改完this指向的函数进行了返回,即返回的是一个函数
constructor(props) {
super(props)
this.state = {
}
// 改变btnClick 的this指向
this.changeWeather= this.changeWeather.bind(this)
}
让 btnClick 指向的是 Weather 实例对象 而不是严格模式下是 undefined
解决组件类中自定义方法的this指向的两种方法
- 使用bind进行重新绑定this
- 使用箭头函数