函数式组件
1 2 3 4 5 6 7 8 9 10 11 12
| function MyComponent(){ console.log(this); return <h2>我是用函数定义的组件(适用于【简单组件】的定义)</h2> } ReactDOM.render(<MyComponent/>,document.getElementById('test'))
|
类式组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class MyComponent extends React.Component { render(){ console.log('render中的this:',this); return <h2>我是用类定义的组件(适用于【复杂组件】的定义)</h2> } } ReactDOM.render(<MyComponent/>,document.getElementById('test'))
|
类的基本知识的复习
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
class Person { constructor(name,age){ this.name = name this.age = age } speak(){ console.log(`我叫${this.name},我年龄是${this.age}`); } }
class Student extends Person { constructor(name,age,grade){ super(name,age) this.grade = grade this.school = '尚硅谷' } speak(){ console.log(`我叫${this.name},我年龄是${this.age},我读的是${this.grade}年级`); this.study() } study(){ console.log('我很努力的学习'); } } class Car { constructor(name,price){ this.name = name this.price = price } a = 1 wheel = 4 static demo = 100 } const c1 = new Car('奔驰c63',199) console.log(c1); console.log(Car.demo);
|
组件的state属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Weather extends React.Component{ constructor(props){ console.log('constructor'); super(props) this.state = {isHot:false,wind:'微风'} this.changeWeather = this.changeWeather.bind(this) }
render(){ console.log('render'); const {isHot,wind} = this.state return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1> }
changeWeather(){ console.log('changeWeather'); const isHot = this.state.isHot this.setState({isHot:!isHot}) console.log(this);
} } ReactDOM.render(<Weather/>,document.getElementById('test'))
|
state属性的简写形式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Weather extends React.Component{ state = {isHot:false,wind:'微风'}
render(){ const {isHot,wind} = this.state return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1> }
changeWeather = ()=>{ const isHot = this.state.isHot this.setState({isHot:!isHot}) } } ReactDOM.render(<Weather/>,document.getElementById('test'))
|
总结
组件中render方法中的this为组件实例对象
组件自定义的方法中this为undefined,如何解决?
强制绑定this: 通过函数对象的bind()
箭头函数
状态数据,不能直接修改或更新