前言
React的组件学习笔记
类组件
传送门
函数式组件
传送门
Fragment
- 片段在渲染后不会产生新的DOM节点
- 通过片段包裹可能有多个根的组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import React from "react";
class Component extends React.Component { render() { return ( <Fragment> <div></div> <div></div> </Fragment> ); } }
export default Component;
|
如果<Fragment></Fragment>组件在使用时不需要属性,可以使用<></>代替
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import React from "react";
class Component extends React.Component { render() { return ( <> <div></div> <div></div> </> ); } }
export default Component;
|
Portal
1 2 3 4 5 6 7 8 9 10 11 12 13
| import React from "react"; import { createPortal } from "react-dom";
class Component extends React.Component { render() { return createPortal( <></>, document.body ); } }
export default Component;
|
高阶组件
- 一个函数,如果入参是一个React组件,出参也是一个React组件,那么这个函数就是高阶组件
1 2 3 4 5 6 7 8 9 10 11
| function HOC(WrapperComponent) { return class Component extends React.Component { render() { return ( <> <WrapperComponent /> </> ); } } }
|
1 2 3 4 5 6 7 8 9
| function HOC(WrapperComponent) { return function Component(props) { return ( <> <WrapperComponent /> </> ); } }
|
严格模式
- 严格模式在渲染后不会产生新的DOM节点
- 严格模式在开发模式下,可以为后代元素触发额外的检测和警告,在构建时不会有任何效果
- 严格模式识别的内容
- 检测过期的生命周期函数
- 检测过期的API调用
- 严格模式故意在某些生命周期执行两次,以发现意外的副作用
1 2 3 4 5 6 7 8 9 10 11 12 13
| import React from "react";
class Component extends React.Component { render() { return ( <React.StrictMode> <div></div> </React.StrictMode> ); } }
export default Component;
|
完成