PureComonent默认给类组件添加了一个shouldComponentUpdate的钩子函数,在这个钩子中,会对新旧状态及属性做一个浅比较,以此达到优化组件渲染的目的。
给需要获取dom的元素设置ref='xxx',然后使用this.refs.xxx进行获取,不建议使用,在React.StrictMode模式下会报错
render() {return 温馨提示
;
}
componentDidMount() {console.log(this.refs.titleBox);
}
将ref设置为一个函数,并将ref的形参(dom元素)挂载到实例上
render() {return this.box2 = x}>友情提示
;
}
componentDidMount() {console.log(this.box2);
}
基于React.createRef()创建一个ref对象,初始化时为null
box3 = React.createRef();render() {return 郑重提示
;
}
componentDidMount() {console.log(this.box3.current);
}
类组件:获取当前组件的实例,通常用于父子组件传值及方法调用
class Demo extends React.Component {render() {return //子组件 this.child1 = x} /> ;}componentDidMount() {console.log(this.child1);}
}
函数组件:获取函数组件内部某个元素。需要使用React.forwardRef()包裹子组件,这是函数子组件将拥有除props外的另一个形参:ref。通过把该形参设置给函数子组件中的某个元素,来达到获取函数子组件中dom元素的目的。
import React from "react";const Child2 = React.forwardRef(function Child2(props, ref) {// 该ref形参为给子组件设置的ref值: x => this.child2 = xreturn 子组件2;
});class Demo extends React.Component {render() {return this.child2 = x} /> ;}componentDidMount() {console.log(this.child2); //子组件内部的button按钮}
}
基于子组件中props.children获取传递的插槽信息(子节点信息)。
+ 调用组件时,基于双闭合调用方式把插槽信息(子节点信息)传递给组件,组件内部进行渲 染
const DemoOne = function Demo(props) {let { title, children } = props;return {title}
{children};
};//传递时
//编译为vdom后作为props.children的值我是插槽内容
具名插槽
import React from 'react';
const DemoOne = function Demo(props) {let { title, children } = props;// 对children的类型做处理// 可以基于 React.Children 对象中提供的方法,对props.children做处理: count\forEach\map\toArray... 在这些方法的内部,已经对children的各种形式做了处理children = React.Children.toArray(children);let headerSlot = [],footerSlot = [],defaultSlot = [];children.forEach(child => {// 传递进来的插槽信息,都是编译为virtualDOM后传递进来的,而不是传递的标签let { slot } = child.props;if (slot === 'header') {headerSlot.push(child);} else if (slot === 'footer') {footerSlot.push(child);} else {defaultSlot.push(child);}});return {headerSlot}
{title}
{footerSlot};
};我是页脚我是匿名的我是页眉