[英]Unable to remove child from useRef hook
I have the following useRef
which contains 4 children.我有以下
useRef
,其中包含 4 个孩子。
I am trying to remove a child from here based on an if check.我试图根据 if 检查从这里删除一个孩子。
But getting the error:但得到错误:
typeError: myRef.current.removeChild is not a function.
But looking at the answers here this seems to be correct.但是看看这里的答案,这似乎是正确的。 What am I doing wrong?
我究竟做错了什么?
How to remove the child element of a div in react using useRef hook? 如何使用useRef钩子在反应中删除div的子元素?
//This is coming from another file. Just for reference.
const myRef = React.useRef();
export const postData = (
myRef,
token,
id1,
id2,
) => {
myRef.current.children[0].value = token;
myRef.current.children[1].value = id1;
myRef.current.children[2].value = id2;
[...myRef.current.children].forEach((child) => {
if (!child.value) {
// error on this line
myRef.current.removeChild(child);
}
});
};
you can use useEffect
hook in here, maybe this will solve your issue.你可以在这里使用
useEffect
钩子,也许这会解决你的问题。
...
const myRef = useRef(null)
useEffect(() => {
myRef.current.children[0].value = token;
myRef.current.children[1].value = id1;
myRef.current.children[2].value = id2;
[...myRef.current.children].forEach((child) => {
if (!child.value) {
myRef.current.removeChild(child);
}
});
}, [myRef.current, child.value])
return (
<div ref={myRef}>
...
</div>
)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.