如何在 Material-UI 菜单中使用自定义功能组件

Bli*_*itz 8 reactjs material-ui react-hooks

我正在使用 Material-UI 来设计我正在构建的 React 应用程序。我正在尝试在组件内使用我自己的自定义功能组件,但出现<Menu>了一个奇怪的错误:

Warning: Function components cannot be given refs.
Attempts to access this ref will fail.
Did you mean to use React.forwardRef()?

Check the render method of ForwardRef(Menu).
    in TextDivider (at Filter.js:32)
Run Code Online (Sandbox Code Playgroud)

发生这种情况的 JSX 如下所示:(第 32 行是 TextDivider 组件)

<Menu>
    <TextDivider text="Filter Categories" />
    <MenuItem>...</MenuItem>
</Menu>
Run Code Online (Sandbox Code Playgroud)

TextDivider 在哪里:

const TextDivider = ({ text }) => {
    const [width, setWidth] = useState(null);
    const style = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    };

    const hrStyle = {
        width: `calc(100% - ${width}px)`,
        marginRight: 0,
        marginLeft: 0
    };

    const spanStyle = {
        color: '#555',
        whiteSpace: 'nowrap'
    };

    const ref = createRef();
    useEffect(() => {
        if (ref.current) {
            const width = ref.current.getBoundingClientRect().width + 35;
            console.log('width', width);
            setWidth(width);
        }
    }, [ref.current]);

    return (
        <div style={style}>
            <span ref={ref} style={spanStyle}>{ text }</span>
            <Divider className="divider-w-text" style={ hrStyle }/>
        </div>
    );
};
Run Code Online (Sandbox Code Playgroud)

奇怪的是,这个组件在常规容器中自行设置时呈现得非常好,但似乎只有在<Menu>组件内部呈现时才会抛出此错误。

此外,我发现如果我像这样将 TextDivider 包装在一个 div 中,这个错误就会完全消失,这真的很奇怪:

<Menu>
    <div>
        <TextDivider text="Filter Categories" />
    </div>
    <MenuItem>...</MenuItem>
</Menu>
Run Code Online (Sandbox Code Playgroud)

然而,这对我来说就像胶带一样,我宁愿理解为什么我不能在菜单中渲染这个组件的潜在问题。我没有在我的功能组件中使用任何类型的 Material-UI ref,也没有在<Divider>组件内的<TextDivider>组件上放置 ref,所以我不明白它为什么会抛出这个错误。

任何有关为什么会发生这种行为的见解将不胜感激。

我尝试使用useCallback钩子、createRef()useRef()和阅读我能找到的关于在功能组件中使用钩子的所有内容。错误本身似乎具有误导性,因为即使是 react 文档本身也使用功能组件参考在这里显示:https : //reactjs.org/docs/hooks-reference.html#useref

Rya*_*ell 15

Menu使用 Menu 的第一个子项作为 Menu 内部使用的 Popover 组件的“内容锚点”。“内容锚点”是菜单内的 DOM 元素,Popover 试图将其与锚点元素(菜单外的元素,即定位菜单的参考点)对齐。

为了利用第一个孩子作为内容锚点,Menu 向它添加了一个引用(使用 cloneElement)。为了避免收到您收到的错误(并让定位正常工作),您的函数组件需要将 ref 转发到它呈现的组件之一(通常是最外面的组件 - 在您的情况下为 div)。

当您使用 adiv作为 的直接子级时Menu,您不会收到错误消息,因为 div 可以成功接收 ref。

SakoBu 引用的文档包含有关如何将引用转发到函数组件的详细信息。

结果应该类似于以下内容(但我是在手机上回答这个问题,如果有任何语法错误,请见谅):

const TextDivider = React.forwardRef(({ text }, ref) => {
    const [width, setWidth] = useState(null);
    const style = {
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
    };

    const hrStyle = {
        width: `calc(100% - ${width}px)`,
        marginRight: 0,
        marginLeft: 0
    };

    const spanStyle = {
        color: '#555',
        whiteSpace: 'nowrap'
    };
    // Separate bug here.
    // This should be useRef instead of createRef.
    // I’ve also renamed this ref for clarity, and used "ref" for the forwarded ref.
    const spanRef = React.useRef();
    useEffect(() => {
        if (spanRef.current) {
            const width = spanRef.current.getBoundingClientRect().width + 35;
            console.log('width', width);
            setWidth(width);
        }
    }, [spanRef.current]);

    return (
        <div ref={ref} style={style}>
            <span ref={spanRef} style={spanStyle}>{ text }</span>
            <Divider className="divider-w-text" style={ hrStyle }/>
        </div>
    );
});
Run Code Online (Sandbox Code Playgroud)

您可能还会发现以下答案很有用:

`useRef` 和 `createRef` 有什么区别?

  • 我不是核心团队的一员,但我是 Material-UI 的积极贡献者,我对 v4 的“Menu”进行了重大改进,因此我非常熟悉它的内部工作方式。 (3认同)