简体   繁体   English

在 React 中,我收到警告:无法为函数组件提供 refs。 尝试访问此 ref 将失败。 你的意思是使用 React.forwardRef() 吗?

[英]In React I get the warning: Function component cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Here's are a few snippets from my code.这是我的代码中的一些片段。 I have a function component defined as:我有一个功能组件定义为:

function AssociationViewer(props) {
    const core = React.useRef<GraphCore | null>(null);
    const dataService = React.useRef<DataService>(new DataService(props.graphApi));
    const selectionBoxDimensions = React.useRef(null);
    const initialGraphRender = React.useRef<boolean>(false);
    const filterRef = React.useRef(null);

    const getElementRef = React.useCallback((el) => {
        if (el && !core.current) {
            core.current = new GraphCore({ container: el });
            // TODO: Change data service to accept core as an argument and initialize it here?
            dataService.current.addGraphDataFn = (opts) => getRksGraph().addData(opts);
            dataService.current.setGraphDataFn = (opts) => getRksGraph().setData(opts);
            onMount();
            return onUnmount;
        }
    }, []);
.
.
.
    return (
        <>
            {props.enableSearch && <div style={{zIndex: 10000, position: 'absolute', marginTop: 10, right: 15}}>
                <button onClick={flashSearchedNodes}>Search</button>
                <input
                    value={searchText}
                    placeholder='Find node by text'
                    onKeyDown={(e) => e.key == 'Enter' && flashSearchedNodes()}
                    onChange={(e) => setSearchText(e.target.value)}
                />
                <input readOnly style={{width: '60px', textAlign: 'center'}} type="text" value={searchedElesDisplayText} />
                <button onClick={prevFoundNode}>Prev</button>
                <button onClick={nextFoundNode}>Next</button>
                <button onClick={cancelFlashNodes}>Clear</button>
            </div>}
            <div
                style={{ height: '100%', width: '100%' }}
                id={props.componentId || 'kms-graph-core-component'}
                ref={getElementRef}
            ></div>
            {core.current && (
                <GraphTooltip
                    tooltip={props.tooltipCallback}
                    tooltipHoverHideDelay={props.tooltipHoverHideDelay}
                    tooltipHoverShowDelay={props.tooltipHoverShowDelay}
                    tippyOptions={props.tippyOptions}
                    core={core.current}
                />
            )}
            {props.loadingMask && !hasCustomLoadMask() && (
                <DefaultLoadMask
                    active={showLoading}
                    loadingClass={getLoadingClass()}
                    onClick={() => {
                        setShowLoading(false);
                    }}
                />
            )}
            {props.loadingMask && showLoading && hasCustomLoadMask() && props.customLoadingMask()}
        </>
    );
}

export default AssociationViewer;

I have an angular app that uses a service to call this component as follows:我有一个角度应用程序,它使用服务来调用这个组件,如下所示:

ReactService.render(AssociationViewer,
{
     ref: function (el) {
          reactElement = el;
     },
     component: 'association-viewer-1',
     getImageUrl: getImageUrl,
     graphApi: graphApi,
     pairElements: $ctrl.pairElements,
     theme: theme,
     view: 'testView'
}
'miniGraphContainer',
() => {
          if ($ctrl.pairElements.edges) {
               reactElement.core.select($ctls.pairElements.edges($ctrl.currEdge).id);
          }
}

Here's GraphTooltip:这是图形工具提示:

import React from 'react';
import GraphCore from '../GraphCore';

function useForceUpdate() {
    const [value, setValue] = React.useState(0);
    return () => setValue((value) => ++value);
}

interface IGraphTooltipProps{
    tooltipHoverShowDelay: number;
    tooltipHoverHideDelay: number;
    core: GraphCore;
    tooltip: Function;
    tippyOptions: any;
}

const GraphTooltip = (props: IGraphTooltipProps) => {
    const tooltipRef = React.useRef<React.Element>(null);
    const forceUpdate = useForceUpdate();

    const setRef = (ref) => {
        tooltipRef.current = ref;
    };

    const [currentElement, setCurrentElement] = React.useState<React.Element>();

    React.useEffect(() => {
        props.core.getAllSubGraphs().forEach((subgraph) => {
            subgraph.setOptions({
                tooltip: {
                    domElementCallback: (e) => {
                        // this isn't changing so it's not picking up a render loop
                        setCurrentElement(e);
                        forceUpdate();
                        return tooltipRef.current;
                    },
                    hoverShowDelay: props.tooltipHoverShowDelay,
                    hoverHideDelay: props.tooltipHoverHideDelay,
                    options: props.tippyOptions
                }
            });
        });
    }, []);

    return <>{props.tooltip(setRef, currentElement, props.core)}</>;
};

export default GraphTooltip;

When triggering the event that causes this ReactService to render the AssociationViewer component, I get the warning: Function component cannot be given refs.当触发导致此 ReactService 呈现 AssociationViewer 组件的事件时,我收到警告:无法为函数组件提供 refs。 Attempts to access this ref will fail.尝试访问此 ref 将失败。 Did you mean to use React.forwardRef()?你的意思是使用 React.forwardRef() 吗? Also, reactElement is undefined since the ref cannot be accessed.此外, reactElement 是未定义的,因为无法访问 ref。 How can I use React.forwardRef() in the AssociationViewer component to forward the ref to the calling component?如何在 AssociationViewer 组件中使用 React.forwardRef() 将 ref 转发到调用组件?

So, here you just have to wrap your functional component inside React.forwardRef()因此,在这里您只需将功能组件包装在React.forwardRef()

<GraphTooltip
    tooltip={props.tooltipCallback}
    tooltipHoverHideDelay={props.tooltipHoverHideDelay}
    tooltipHoverShowDelay={props.tooltipHoverShowDelay}
    tippyOptions={props.tippyOptions}
    core={core.current} // Due to this you are getting warning
/>

Go to your functional component "GraphTooltip" and wrap your export statement in forwardRef().转到您的功能组件“GraphTooltip”并将您的导出语句包装在 forwardRef() 中。

export const React.forwardRef(GraphTooltip)

Hope it helps!希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应:警告:无法为函数组件提供参考。 尝试访问此引用将失败。 你的意思是使用 React.forwardRef() 吗? - React: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? 警告:无法为 Function 组件提供参考。 尝试访问此 ref 将失败。 你是想使用 React.forwardRef() 吗? - Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? 不能为 TypeScript &gt; Function 组件提供 refs。 尝试访问此引用将失败。 你的意思是使用 React.forwardRef() 吗? - TypeScript > Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? 无法为 Function 组件提供参考。 尝试访问此 ref 将失败。 你是想使用 React.forwardRef() 吗? - Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? 如何摆脱错误功能组件不能被赋予参考。 尝试访问此 ref 将失败。 你的意思是使用 React.forwardRef() 吗? - How to get rid off error Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? React hook form v7 Function 组件不能给出参考。 尝试访问此 ref 将失败。 你的意思是使用 React.forwardRef() - React hook form v7 Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef() React Js 错误:Function 组件不能给出参考。 尝试访问此 ref 将失败。 你的意思是使用 React.forwardRef() 吗? - React Js Error : Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? 尝试访问此 ref 将失败。 你的意思是使用 React.forwardRef() - Attempts to access this ref will fail. Did you mean to use React.forwardRef() 函数组件不能有引用。 你的意思是使用 React.forwardRef() 吗? - Function components cannot have refs. Did you mean to use React.forwardRef()? ReactJS:React-Month-Picker 错误:函数组件不能有引用。 你的意思是使用 React.forwardRef() 吗? - ReactJS: React-Month-Picker Error: Function components cannot have refs. Did you mean to use React.forwardRef()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM