react之事件

target

console.log(event.target);//点谁就是谁
console.log(event.currentTarget);//谁最上面就是谁
  • react里面支持很多很多事件,不用背,直接查即可;
  • 类组件里面,render函数中,this指向类的实例。因为箭头函数this与上下文有关。所以,render函数里的箭头函数里的this也指向类的实例;
  • 如果不使用箭头函数,行内使用一般函数,在这个函数了里使用this关键字会报错!解决方法是:
  1. 换回箭头函数吧!
  2. 给一般函数行内绑定this,使this指向类组件实例,like this:
<button onClick = {(function(event){
				
				this.setState({
					name: 'tweety',
					number: ++number
				});
				
				this.setState((newState,props)=>{
					return{
						name:'Flora',
						number:newState.number === 2 ? 2:0
					};
				});
			}).bind(this)}>change number</button>

但是这样会产生不好的影响,bind之后会更新button,造成不必要的资源浪费。所以,不要在行内绑定事件的回调函数,在构造函数中绑定好。 like this:

constructor(props){

		super(props);
		
		this.state = {
			name: props.name,
			number: props.number
		};
		this.handdleButtonClick = this.handdleButtonClick.bind(this);
		this.handdleDivClick = this.handdleDivClick.bind(this);
	}

所以这样的话,只要你使用一个事件回调函数,并且函数里面需要用到this,你就得在构造函数里面来上这么一句。但当事件回调函数很多很多时,怎么办呢?我们可以在构造函数删掉这种话,然后对回调函数施加ES6的一种语法:类属性语法! like this:

handdleButtonClick = (event)=>{
		let {name, number} = this.state;
		this.setState({
					name: 'tweety',
					number: ++number
				});
				
		this.setState((newState,props)=>{
					return{
						name:'Flora',
						number:newState.number === 2 ? 2:0
					};
				});
		console.log("我是button");
	}

这样使,函数变得好像一个箭头函数哟~

生命周期

只有类组件才有生命周期,函数式组件没有生命周期

Mount阶段———出生

函数调用顺序如下:

  1. constructor (一生调用一次)

  2. static getDerivedFromProps(props,state) (更新时也要调用):
    在你调用render之前,给你一次改变state的机会,不想改变就返回null

  3. render (有可能更新时也要调用)

  4. componentDidMount (一生调用一次):
    此刻,可以访问DOM元素了

Update阶段———更新

  1. 使用static getDerivedFromProps(props,state)来使子组件同步父组件的更新;
  2. shouldComponentUpdate(nextProps, prevState)
    用于优化性能,返回一个布尔值。
    true:组件进行正常更新流程;
    false:后面的生命周期函数不会执行,界面不会更新。
  3. render
  4. getSnapshotBeforeUpdate(prevProp, prevState)
    它执行的时候,新的虚拟DOM已经生成了,但是还没有渲染到浏览器页面中。
  5. componentDidUpdate
    更新已经完成时调用
    它将接受getSnapshotBeforeUpdate(prevProp, prevState)的返回值
    此刻,可以访问DOM元素了!

Unmounting阶段———卸载

componentWillUnmount (一生调用一次)

错误处理阶段

componentDidCatch(error,info)
捕捉子组件生命周期中抛出的错误

react标准化运行

  1. cd到相应目录
  2. cnpm run build
  3. 安装静态服务器来运行html,npm i -g serve
  4. npx serve -s build
原文地址:https://www.cnblogs.com/endymion/p/9323943.html