const myComp = () => {
const myRef = useRef();
useEffect(() => {
if (!myRef.current) return;
const element = document.createElement('div');
element.setAttribute('id', 'some-id');
myRef.current.appendChild(element);
// wrapperElement is `undefined`
const wrapperElement = document.getElementById('some-id')
// this will trigger error - see comment above
wrapperElement
.appendChild(document.createElement('iframe'));
}
}, [ myRef ]);
当元素是 ref 元素的子元素(或存储在 ref 元素本身中)时,有没有办法通过 id 获取元素?
目标是允许外部库获取包装器并在其中加载 iframe。我无法控制外部库
用例示例:Youtube 播放器 iframe,当通过包装器 id 而不是实际元素初始化时。我知道 Youtube 播放器允许传递实际元素(即myRef.current
)而不是包装器 id,但解决方案必须是通用的,并且应该只使用元素 id