1.JSX
作用:简化创建虚拟DOM
写法:
var name = <h1>Hello JSX!<h1>
JSX表达式最后编译得到的就是一个JS对象
语法规则
(1) 遇到 <开头的代码, 以标签的语法解析: html同名标签转换为html同名元素, 其它标签需要特别解析
(2) 遇到以 { 开头的代码,以JS语法解析: 标签中的js表达式必须用{ }包含
(3)属性名称定义采用小驼峰命名法 如className tabbar、tabBar for
(4)所有标签外围只允许有一个根标签
(5)标签必须闭合,组件标签首字母须大写
2.组件
2.1 State
state是组件对象最重要的属性, 值是对象(可以包含多个key-value的组合)。通过对组件的state的更新来更新对应的页面显示(组件冲渲染)
注意
- 组件中render方法中的this为组件实例对象
- render函数中的this指向的也是组件实例对象
- 状态数据,不能直接修改或更新
- 只有通过组件实例对象调用类中的方法,this才指向该实例对象
- 组件自定义的方法中this为undefined,如何解决?
- 强制绑定this: 通过函数对象的bind()
- 箭头函数
2.2 props
每个组件对象都会有props属性,组件标签所有属性都保存在其中。
props通过标签属性从组件外向组件内传递变化的数据。
注意:组件内部不要修改props数据
读取某个属性值
this.props.name
对属性值进行限制(使用prop-types库)
Student.propTypes = {
name: ProTypes.string.isRequired,
age: ProTypes.numer.
}
传递对象属性
<Student {...Student}/>
设置默认值
Student.defaultProps = {
age: 18,
sex: '男'
}
组件类构造函数
constructor(props){
super(props)
console.log(props)//打印所有属性
}
2.3 refs
组件内的标签可以定义ref属性来标识自己
字符串形式ref
<input ref="input1"/>
回调形式ref
<input ref={(c)=>{this.input1 = c}}/>
createRef创建ref容器
myRef = React.createRef()
<input ref={this.myRef}/>
3.组件生命周期
- 初始化阶段: 由ReactDOM.render()触发---初次渲染
- constructor()
- getDerivedStateFromProps
- render()
- componentDidMount()
- 更新阶段: 由组件内部this.setSate()或父组件重新render触发
- getDerivedStateFromProps
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate
- componentDidUpdate()
- 卸载组件: 由ReactDOM.unmountComponentAtNode()触发
- componentWillUnmount()
重要的hook
- render:初始化渲染或更新渲染调用
- componentDidMount:开启监听, 发送ajax请求
- componentWillUnmount:做一些收尾工作, 如: 清理定时器