编辑:更好的解释
上下文:
我从第三台服务器收到一些纯 HTML 代码,我想
原版 JS 方法
id
的 HTML 标记getElementById
修改这些元素, 像往常一样 React 方法
ReactDOMServer.renderToString
ReactDOM.render()
注入(inject)组件时,问题是 render
方法需要时间,因此如果在下一行中我尝试使用插入组件中存在的 ref,则还没有 问题
useEffect
中与 []
依赖关系,但我在这里 rendering
应用已挂载时的组件ref
,但肯定有更好的东西此代码失败,因为当
ref
渲染它仍然不可用,所以 ref.current
未定义我怎么能等到呢?
codesandbox
编辑:我提供了有效的代码,但通过直接 DOM,我认为应该避免
import React, { useRef, useEffect } from "react";
import ReactDOM from "react-dom";
export default function App() {
const myref = useRef();
useEffect(() => {
const Com = () => <div ref={myref}>hello</div>;
ReactDOM.render(<Com />, document.getElementById("container"));
console.log(myref.current); // undefined
document.getElementById('container').textContent = "direct DOM works"
// the next line fails since the ref is not yet available
// myref.current.textContent = "but this REF is not available"; // fails
}, []);
const plainhtml = '<div><div id="container"></div><div>some more content</div><div id="another">even more content</div></div>'; // this is some large HTML fetched from an external server
return (
<div>
<h1>Hello CodeSandbox</h1>
<div dangerouslySetInnerHTML={{ __html: plainhtml }} />
</div>
);
}
最佳答案
useEffect
使用空依赖数组执行 之后 第一次渲染,因此您将在回调中获得 DOM ref:
const htmlString = '<div id="container">Hello</div>';
export default function App() {
const myRef = useRef();
useEffect(() => {
if (myRef.current) {
myRef.current.textContent = 'whats up';
}
console.log(myRef.current);
}, []);
return (
<div>
<div ref={myRef} dangerouslySetInnerHTML={{ __html: htmlString }} />
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
</div>
);
}
/* App renders:
whats up
Hello
*/
关于javascript - react : How to wait until ref is available when inserted (rendered) within a second container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61408146/