2.2 操作JSX
2.2.1 JSX与Element对象
JSX在编译阶段就会转换成createElement形式,执行createElement会得到ReactElement对象;
组件和元素的区别是,元素的type属性为对应的元素标签类型,组件的type属性为对应的组件函数或组件类本身(相同的内存空间)
2.2.2 Element方法集
cloneElement作用:createElement作用是把开发者写的JSX转换成Element对象;cloneElement的作用则是以Element元素为样板克隆并返回新的React元素。返回元素的props是将新的props与原始元素的props千层哼后的结果
用法:
React.cloneElement( element, [props], [...children] )备注:
element:需要克隆的element对象
props:需要合并的props
其他children:新的Children元素,依次排列
isValidElement可以用来判断是否为React Element对象
用法
React.isValidElement(element)备注:
element:待验证元素
返回true:是React Element对象,反之不是
Children方法集JSX闭合标签的内容叫做React Children,会绑定在闭合标签对应的Element的props属性上
举例:
<WrapComponent> <Text /> <Text /> <Text /> <span>hello, world</span> </WrapComponent>WrapComponent组件会被转成Element结构,三个Text和一个span会绑定在element.props.children
这种数据结构无法正常遍历了,即便遍历也无法有效遍历到每一个元素,需要使用React.Children方法集来解决
React.Children.map类似数组的map方法,返回一个新的Children数组
用法:
React.Children.map( children, fn )示例
function WrapComponent(props) { const newChildren = React.Children.map(props.children, (item)=>item) console.log(newChildren) return newChildren }备注:
上过上述操作,newChildren就变成了一个透明的数组结构;
如果Children是一个Fragment对象,它将被视为单一子节点,不会被遍历
React.Children.forEach与React.Children.map用法类似,React.Children.map可以返回新的数,React.Children.forEach只停留在遍历阶段
示例:
React.Children.forEach(props.children,(item)=>console.log(item))
React.Children.count用于获取子元素的总数量,等同于map或forEach调用回调函数的次数;对于更复杂的结果,可以返回同一级别子组件的数量
示例
const childrenCount = React.Children.count(props.children) console.log(childrenCount,'childrenCount')
React.Children.toArray用于返回props.children扁平化的结果
示例:
const newChildrenArray = React.Children.toArray(props.children) console.log(newChildrenArray, 'newChildrenArray')Children.toArray不但可以扁平化、规范化Children组成的数组,只要hildren中的数组元素被打开
Children.toArray在展开子节点列表时,会更改key值,以保留嵌套数组的语义
React.Children.Only验证Children是否只有一个子节点(一个React元素),有,返回,否则报错
示例
console.log(React.Children.only(props.children))
2.2.3 Element对象持久化
React应用更新的时候,本质上是通过createElement重新创建element对象,如果想要保存Element对象,下一次更新时不会被重新创建,可以将其保存下来编程持久化
组件类实现:
函数组件useRef
注意:必须手动更新Element
函数组件useMemo(推荐)
备注:当依赖项value改变的时候,可以重新生成Text组件的Element对象
最后更新于