
以下是一些更高级的 react 概念和术语:
12。上下文 api
context api 提供了一种通过组件树传递数据的方法,而无需在每个级别手动传递 props。它对于主题、身份验证或用户数据等全局数据很有用。
示例:
const themecontext = react.createcontext('light');
function themedbutton() {
return (
{theme => }
);
}
function app() {
return (
);
}
13。参考文献
refs 提供了一种访问 dom 节点或在 render 方法中创建的 react 元素的方法。它通常用于直接修改 dom 元素或管理焦点。
示例:
import { useref } from 'react';
function textinputwithfocusbutton() {
const inputel = useref(null);
const onbuttonclick = () => {
inputel.current.focus();
};
return (
);
}
14。高阶组件 (hoc)
hoc 是一个接受组件并返回新组件的函数。它经常用于重用组件逻辑。
示例:
function withlogger(wrappedcomponent) {
return function withlogger(props) {
console.log('rendering component');
return ;
};
}
const enhancedcomponent = withlogger(mycomponent);
15。 react.memo
react.memo 是一个高阶组件,它通过记忆组件来帮助优化性能。如果 props 没有改变,组件将跳过重新渲染。
示例:
const mycomponent = react.memo(function mycomponent(props) {
return {props.text};
});
16。使用reducer hook
usereducer 钩子是 usestate 的替代方案。它对于管理更复杂的状态逻辑非常有用,特别是当状态依赖于先前的值时。
示例:
import { usereducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new error();
}
}
function counter() {
const [state, dispatch] = usereducer(reducer, { count: 0 });
return (
{state.count}
);
}
17。反应片段
react fragments 让您可以对子级列表进行分组,而无需向 dom 添加额外的节点。
示例:
function table() {
return (
<>
row 1
row 2
>
);
}
18。传送门
门户提供了一种将子组件渲染到父组件层次结构之外的 dom 节点的方法。
示例:
import reactdom from 'react-dom';
function modal({ children }) {
return reactdom.createportal(
{children},
document.getelementbyid('modal-root')
);
}
19。误差边界
错误边界是 react 组件,可以在其子组件树中的任何位置捕获 javascript 错误,记录这些错误并显示后备 ui。
示例:
class errorboundary extends react.component {
constructor(props) {
super(props);
this.state = { haserror: false };
}
static getderivedstatefromerror(error) {
return { haserror: true };
}
render() {
if (this.state.haserror) {
return something went wrong.
;
}
return this.props.children;
}
}
20。延迟加载
react 支持组件延迟加载,这意味着组件可以在需要时异步加载,从而提高大型应用程序的性能。
示例:
import react, { suspense } from 'react';
const othercomponent = react.lazy(() => import('./othercomponent'));
function mycomponent() {
return (
loading...










