基本使用
react 不是一个完整的 MVC 框架,它是 V ( View ) 那一层。
jsx使用
- 表达式
- 判断
- 循环
bind this 事件
this默认为undefined
this.handleChange = this.handleChange.bind(this)handleChange (){} // this默认为undefined// 静态方法handleChange = () => {this.setState({name: 'wq'})}
event
注意: 和vue的event不一样,vue是原生event(MouseEvent)
<a href="https://www.baidu.com" onClick={(event) => {event.preventDefault()event.stopPropagation()console.log(event)console.log(event.nativeEvent)// 此处event不是原生的event,而是组合event(SyntheticBaseEvent)}}>click me</a>
event.nativeEvent 才是原生事件
所有事件都被绑定到 document 上(React16),而 React17 是绑定到 root 组件上(有利于多个react版本并存,例如微前端)
和 DOM 事件不一样,和 vue 事件也不一样
传递自定义参数
受控组件
<label htmlFor="inputName">姓名:</label><input type="text" id="inputName" value={name} onChange={(e) => setName(e.target.value)} />
非受控组件
父子组件通信
- props 传递数据
- props 传递函数
- props 类型检查
- PropTypes 库
状态(数据)提升
setState(重要)
- 不可变值
- 设置时,不能影响到之前的值 ```jsx // 不要直接修改 state, 使用不可变值 this.state.count++ // 错误
// 数组, 对象 this.setState({ list1: this.state.list1.concat(100) }) // … , concat, slice, filter
this.setState({ obj: Object.assign({}, this.state.obj, {a: 100}), obj1: {…this.state.obj, a: 100}, })
- **可能是异步更新<br />**```jsxconstructor(props) {this.state = {count: 0}}this.setState({count: this.state.count + 1}, () => {// vue的nextTickconsole.log('回调', this.state.count) // 1})console.log(this.state.count) // 0, 拿不到最新的值,异步的// setTimeout 同步的setTimeout(() => {this.setState({count: this.state.count + 1})console.log('setTimeout', this.state.count) // 1 , 此处同步}, 0)
import React from "react";interface Props {}interface StateType {count: number;}class Header extends React.Component<Props, StateType> {constructor(props: Props) {super(props);this.state = {count: 0,};}bodyClickHandler () {this.setState({count: this.state.count + 1,});console.log("count in body event", this.state.count);}componentDidMount() {// 自定义DOM事件,setState同步的document.body.addEventListener("click", this.bodyClickHandler);}componentWillUnmount() {// 及时销毁document.body.removeEventListener('click', this.bodyClickHandler)}render() {return <div>111</div>;}}
- 可能会被合并
- 传入对象,会被合并(类似 Object.assign),执行结果只一次 +1
- 传入函数,不会被合并
// 传入对象,会被合并,执行结果只一次 +1 (类似 Object.assign)this.setState({count: this.state.count + 1,});this.setState({count: this.state.count + 1,});this.setState({count: this.state.count + 1,}); // 1
// 传入函数,不会被合并,执行结果+3this.setState((prevState, props) => {return {count: prevState.count + 1,}});this.setState((prevState, props) => {return {count: prevState.count + 1,}});this.setState((prevState, props) => {return {count: prevState.count + 1,}});
组件生命周期
https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/


