JSX
语法规则
跟标签只有一个
标签必须闭合
内联样式style={{}}
类名:className。
标签中混入js表达式时,使用{}
标签首字母
(1)小写转换为html中的同名标签,若没有,则报错
(2)若为大写,react就去渲染对应的组件。若组件没有定义,就报错。
函数式组件:
function MyComment(){
return <h2> 这是用函数式声明定义的组件</h2>
}
ReactDOM.render(<MyComment/>,document.getElementById('test'))
类复习:
class Person{
constructor(name,age){
//构造器的this是类的实例对象
this.name=name
this.age=age
}
//一般方法:speak放在了类的原型对象上,
//通过类实例调用时,this指向实例对象
speak(){
console.log(`我叫${this.name},我的年龄是${this.age}`);
}
}
// const p1=new Person('tom',18);
// console.log(p1);
class Student extends Person{
constructor(name,age,grade){
//在子类中使用构造器时,必须调用super()
//传入共有属性
super(name,age)//
this.grade=grade
}
//重写从父类继承的方法
speak(){
console.log(`我叫${this.name},我的年龄是${this.age},${this.grade}`);
}
}
类式组件
class Weather extends React.Component{
//构造器调用几次? ———— 1次
constructor(props){
console.log('constructor');
super(props)
//初始化状态
this.state = {isHot:false,wind:'微风'}
//解决changeWeather中this指向问题
this.changeWeather = this.changeWeather.bind(this)
}
//render调用几次? ———— 1+n次 1是初始化的那次 n是状态更新的次数
render(){
console.log('render');
//读取状态
const {isHot,wind} = this.state
return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
}
//changeWeather调用几次? ———— 点几次调几次
changeWeather(){
//changeWeather放在哪里? ———— Weather的原型对象上,供实例使用
//由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
//类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined
console.log('changeWeather');
//获取原来的isHot值
const isHot = this.state.isHot
//严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
this.setState({isHot:!isHot})
console.log(this);
//严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
//this.state.isHot = !isHot //这是错误的写法
}
}
//2.渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'))
简写:
class Weather extends React.Component{
//初始化状态
state = {isHot:false,wind:'微风'}
render(){
const {isHot,wind} = this.state
return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
}
//自定义方法————要用赋值语句的形式+箭头函数
//箭头函数的this向外层寻找,指向weather实例对象
changeWeather = ()=>{
const isHot = this.state.isHot
this.setState({isHot:!isHot})
}
}
//2.渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'))
函数式组件和类式组件的区别:
1,类组件可以使用state,和生命周期钩子。
2.函数式组件更加高效,因为类组件需要react进行实例化,而函数式组件直接执行函数返回结果就行。
3.函数式组件没有this,没有生命周期,没有state。