为什么在React中使用useImperitaveHandle钩子?

问题描述

我找不到useImperativeHandle Hook的用例。在尝试使用Google并了解我的过程中,我遇到了一个代码沙箱,其中显示了为什么要使用useImperitaveHandle Hook的示例。这是codesandBox链接

https://codesandbox.io/s/useimperativehandle-example-forked-illie?file=/src/App.js

修改代码,以使其在没有下面的codeandBox链接中的useImperitaveHandle的情况下工作。有人可以解释为什么使用该挂钩吗,因为我相信没有它就可以编写代码以提供完全相同的功能

https://codesandbox.io/s/useimperativehandle-example-forked-2cjdc?file=/src/App.js

解决方法

我找到了一个使用该示例的示例。根据我的理解,如果您需要为某个库编写一些自定义功能,并且需要某些库的内置功能,则将主要需要它。

在我将提供的示例中,我将为库ag-grid(表库)编写一个自定义CellEditor,因为我想使用Material UI的自动完成功能在表中选择单元格的值。下面是代码

import React,{ useState,forwardRef,useImperativeHandle } from "react";

import MuiTextField from "@material-ui/core/TextField";
import MuiAutocomplete from "@material-ui/lab/Autocomplete";

const AutocompleteEditor = forwardRef(
  ({ fieldToSave,fieldToShow,textFieldProps,options,...props },ref) => {
    const [value,setValue] = useState("");

    useImperativeHandle(ref,() => {
      return {
        getValue: () => {
          return value;
        },afterGuiAttached: () => {
          setValue(props.value);
        },};
    });

    const tranformValue = (value,fieldtosave) =>
      Array.isArray(value)
        ? value.map((v) => v[fieldtosave] || v)
        : value[fieldtosave];

    function onChangeHandler(e,value) {
      setValue(value ? tranformValue(value,fieldToSave) : null);
    }

    return (
      <MuiAutocomplete
        style={{ padding: "0 10px" }}
        options={options}
        getOptionLabel={(item) => {
          return typeof item === "string" || typeof item === "number"
            ? props.options.find((i) => i[fieldToSave] === item)[fieldToShow]
            : item[fieldToShow];
        }}
        getOptionSelected={(item,current) => {
          return item[fieldToSave] === current;
        }}
        value={value}
        onChange={onChangeHandler}
        disableClearable
        renderInput={(params) => (
          <MuiTextField
            {...params}
            {...textFieldProps}
            style={{ padding: "5px 0" }}
            placeholder={"Select " + props.column.colId}
          />
        )}
      />
    );
  }
);

export default AutocompleteEditor;

如果知道自动补全部分,对理解useImperativeHandler也不重要

所以要解释代码的作用。以上组件的值由用户通过“自动完成”设置,但是ag-grid表也需要该值,因为它需要更新相应单元格中的值。

它在内部使用一个传递给customCellEditor的引用。然后,useImperativeHook告诉ag-grid在调用getValue时使用组件状态中的值(当单元格需要显示值时调用该值)