【问题标题】:React component reference own DOM-element in typescriptReact 组件在 typescript 中引用自己的 DOM 元素
【发布时间】:2020-02-23 17:02:56
【问题描述】:

对 React 还是很陌生,我遇到了以下问题: 我正在以这种方式创建一个组件:

export const CSpiderWeb = (props: iSpiderWebProps) => {
    const classes = useStyles();
    const [drawingObject, setDrawingObject] = useState({} as iDrawingObject);

    const _InitRaphael = (target : HTMLDivElement) => {
        while (target.firstChild) {
            target.removeChild(target.firstChild);
        }

        const workDrawingObject : iDrawingObject = {
            width : target.offsetWidth,
            height : target.offsetHeight,
            centerX : target.offsetWidth / 2,
            centerY : target.offsetHeight /2
        }

        workDrawingObject.paper = Raphael(target, workDrawingObject.width, workDrawingObject.height);

        setDrawingObject(workDrawingObject);
    }


    var workRef = createRef<HTMLDivElement>();
    _InitRaphael(workRef.current as HTMLDivElement);

    return <div ref={workRef} className={classes.paperContainer}>{drawingObject.centerX}x{drawingObject.centerY}</div>
}

我在这里尝试完成的是获取渲染的 DIV 元素并将其传递给 _InitRaphael 方法,但似乎这是在渲染元素之前调用的。 有道理,但如何做到这一点。我用谷歌搜索和搜索,有时我遇到了 componentDidMount 钩子,但可以在这里使用吗?如果是这样,那么如何?

【问题讨论】:

    标签: reactjs typescript components


    【解决方案1】:

    您不能使用componentDidMount,因为它只能在class components 中使用,当您使用function component 时,如在您的示例中使用hooks https://reactjs.org/docs/hooks-effect.html

    我建议你使用模仿componentDidMountuseEffect 钩子。

    【讨论】:

    • 两个答案相似,所以我将第一个标记为正确。
    【解决方案2】:

    您应该考虑使用 useEffect 挂钩。它在渲染完成后调用,因此 ref 应该具有值。

    useEffect(() => {
      _InitRaphael(workRef.current as HTMLDivElement);
    }, [])
    

    但是除非你使用外部的非 React 库,否则你不应该使用这种模式。在 React 应用程序中,引用的使用是例外,而不是正常的做事方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 2019-05-01
      • 2017-10-09
      相关资源
      最近更新 更多