Skip to main content

React

useImperativeHandle

  • 官方文档
  • useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值。在大多数情况下,应当避免使用 ref 这样的命令式代码。useImperativeHandle 应当与 forwardRef 一起使用
//父组件
import { useRef } from 'react';
const curRef: MutableRefObject<{ getFiles: Function } | undefined> = useRef();
curRef.current?.getFiles(); //调用子组件方法或者获取数据

<MailFiles ref={curRef} />;

//子组件
import { useState, useImperativeHandle, forwardRef } from 'react';
const MailFiles = forwardRef((props, ref) => {
const [files, setFiles] = useState<UploadFileType[]>([]);

useImperativeHandle(ref, () => {
return {
getFiles: () => files,
};
});
});

⬆ back to top

normalize

  • 使用 create-react-app 创建的项目,app.css 下添加
@import-normalize; /* bring in normalize.css styles */

⬆ back to top

setState 直接更新数组元素

this.setState({ [list[{ index }]]: item });

⬆ back to top

Code-Splitting

⬆ back to top

错误边界 Error Boundaries

class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染能够显示降级后的 UI
return { hasError: true };
}

componentDidCatch(error, errorInfo) {
// 你同样可以将错误日志上报给服务器
logErrorToMyService(error, errorInfo);
}

render() {
if (this.state.hasError) {
// 你可以自定义降级后的 UI 并渲染
return <h1>Something went wrong.</h1>;
}

return this.props.children;
}
}

⬆ back to top

替换 Moment ant design

//自定义组件 新建 src/components/DatePicker.tsx
import { Dayjs } from 'dayjs';
import dayjsGenerateConfig from 'rc-picker/es/generate/dayjs';
import generatePicker from 'antd/es/date-picker/generatePicker';
import 'antd/es/date-picker/style/index';

const DatePicker = generatePicker<Dayjs>(dayjsGenerateConfig);
export default DatePicker;

//导出自定义组件 src/components/index.tsx
export { default as DatePicker } from './DatePicker';

⬆ back to top

React-18

  • Property 'createRoot' does not exist on type 'typeof import("/home/zh9956/WebstormProjects/react-18-demo/node_modules/@types/react-dom/index")'.
//tsconfig.json
{
compilerOptions: {
types: ['react/next', 'react-dom/next'],
},
}

⬆ back to top

Property 'Search' does not exist on type 'ForwardRefExoticComponent>'

import Input from './Input';
import Search from './Search';
// const Input = React.forwardRef<HTMLInputElement, Props>((props, ref)...
// const Search = React.forwardRef<HTMLInputElement, Props>((props, ref)...

export type InputComponentType = typeof Input & {
Search: typeof Search;
};

(Input as InputComponentType).Search = Search;

export default Input as InputComponentType;

⬆ back to top

createPortal

ReactDOM.createPortal(child, container);

⬆ back to top

Type 'Timeout' is not assignable to type 'number'

const timer = useRef<number>();

timer.current = setTimeout(() => handler); //Type 'Timeout' is not assignable to type 'number'

//window.setTimeout
timer.current = window.setTimeout(() => handler);

⬆ back to top