1 组件
1 说白了就是一个独立的标签元素
2 常用的创建组件的方式有俩种
3 组件文件名, 要以大写字母开头
4 函数式组件中 props 和 方法调用不需要加 this
5 函数式组件性能优于类组件
6 import {Fragment} from 'react'
7 注意不要直接修改 props 获取的外部数据值
8 组件实例 --> import A1 from './A1' --> <A1/>
2 类组件
------------------------------------------ 1 说明 -----------------------------------------
1 在 constructor 中要使用 this.props , 必须有 super(props) 方法及参数
2 constructor 的俩个作用 --> 初始化 state + 绑定方法
3 constructor 可省略不写 react 会隐式的加一个空的 constructor
4 类组件继承于 React.Component 这个父类, 从而可以使用父类中提供的方法和属性
------------------------------------------ 2 代码范式 -----------------------------------------
import React from 'react'
class A extends React.Component{
constructor(props) {
super(props)
this.state = { msg: 'zhang', ..}
this.log = this.k1.bind(this)
}
k1 = () => {}
k2() {}
render() {
return (
<div>
<button onClick={this.log}> 按钮 </button>
</div>
)
}
}
export default A
------------------------------------------ 3 格式(常用) -----------------------------------------
class A extends React.Component{
state = {hh: '按钮'}
c1 = this.props => console.log(this.props)
render () {
return (<i onClick={this.c1}> {this.state.hh} </i>)
}
}
------------------------------------------ 4 数据修改(常用) -----------------------------------------
1 setState() 用于修改 state 定义的私有数据 + 更新 UI
2 每次执行 this.setState() 都会触发 diff运算, 自动更新对应节点的视图
3 render() / constructor() / componentDidUpdate() / 渲染方法中, 不可以使用 this.setState()
4 通常在功能方法里面, 使用 this.setState()
5 代码范式 (常用)
1 定义数据: state = {name: 'zhang', age: 25}
2 修改数据: this.setState({name: 'wei'}) / this.setState(state => ({age: state.age+1}))
3 函数式组件
const X = props => {
const c1 = () => console.log(props)
return (<i onClick={c1}> 按钮 </i>)
}