【发布时间】:2019-10-21 14:51:26
【问题描述】:
我可以在 react 应用程序中使用 js 创建 svg 及其所有子组件(如 rect 等)。但是我不能给元素 ref 属性。如果我看到生成的源代码,它的 ref=[object Object],因此它不起作用。代码在 componentDidMount 中调用,在 appendChild 之后。所以它应该可以工作,因为它已经在 DOM 中呈现(不是吗?)。 ref 适用于 svg 元素(如果不是动态创建的)。有人能指引我正确的方向吗?
即使使用 React 的 createElement 函数也可以: React.createElement('rect', {key: "myKey", width: 100, height: 100, ref: myRef}) 但它不会创建一个真正的 DOM 节点,它可以与 appendChild 函数一起使用(错误消息是这样说的)。所以我也不能真正使用它。 clipPathRef.current 返回包含的 clipPath 元素,当然可以。 rect 元素被创建和渲染,它只是没有正确的 ref 属性。
const myRef = React.createRef();
const newElement = document.createElementNS("http://www.w3.org/2000/svg", 'rect');
newElement.setAttribute("width", 100);
newElement.setAttribute("height", 100);
clipPathRef.current.appendChild(newElement);
newElement.setAttribute("ref", myRef);
console.log(myRef);//outputs [current null]
【问题讨论】:
-
Ref是一个特殊的JSX属性,放在DOM节点上没有特殊属性