簡體   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()?

這是我的代碼中的一些片段。 我有一個功能組件定義為:

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;

我有一個角度應用程序,它使用服務來調用這個組件,如下所示:

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);
          }
}

這是圖形工具提示:

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;

當觸發導致此 ReactService 呈現 AssociationViewer 組件的事件時,我收到警告:無法為函數組件提供 refs。 嘗試訪問此 ref 將失敗。 你的意思是使用 React.forwardRef() 嗎? 此外, reactElement 是未定義的,因為無法訪問 ref。 如何在 AssociationViewer 組件中使用 React.forwardRef() 將 ref 轉發到調用組件?

因此,在這里您只需將功能組件包裝在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
/>

轉到您的功能組件“GraphTooltip”並將您的導出語句包裝在 forwardRef() 中。

export const React.forwardRef(GraphTooltip)

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM