我有一个简化的react组件结构:
<Content>
<Activity>
<EditableDiv>
</EditableDiv>
</Activity>
</Content>
在<EditableDiv>
中,每当第一个祖先被滚动时,我都想在<EditableDiv>
中调用一个函数。在本例中,<Content>
内部的div是第一个祖先,因此我注册了一个要在其onscroll
事件上调用的函数。
function EditableDiv(props) {
const [value, setValue] = useState(props.value);
const [showActionButtons, setShowActionButtons] = useState({ shown: true });
useEffect(init, []);
function init() {
const el = document.getElementById("main-container");
if (el !== null) {
const scrollParent = UiHelper.getScrollParent(el);
scrollParent.onscroll = function () {
closeActionButtons();
};
}
}
function closeActionButtons() {
setShowActionButtons({ shown: false });
}
return (
<div id="main-container">
</div>
);
}
函数closeActionButtons
被调用(命中断点),但是当它应该隐藏一些按钮时,它似乎什么也不做。现在,我尝试在onclick
组件中注册一个<EditableDiv>
处理程序,并调用相同的closeActionButtons
函数,然后成功地进行隐藏。
在注册到父组件的onscroll
事件的函数中,它似乎不起作用。此外,在我的setValue
中,您可以看到我传递了props.value
(它有一些字符串值)。当我在onscroll
函数中放置一个断点时,props.value
是未定义的,但在onclick
函数中,我传递的原始值将被保留。
发布于 2022-01-11 11:26:37
useRef
useRef
返回一个可变的ref对象,该对象的.current属性初始化为传递的参数(initialValue
)。返回的对象将持续到组件的整个生存期。https://reactjs.org/docs/hooks-reference.html#useref
function EditableDiv(props) {
const containerRef = useRef(null)
const [value, setValue] = useState(props.value);
const [showActionButtons, setShowActionButtons] = useState({
shown: true
});
useEffect(init, []);
function init() {
const el = containerRef.current;
if (el !== null) {
const scrollParent = UiHelper.getScrollParent(el);
scrollParent.onscroll = function() {
closeActionButtons();
};
}
}
function closeActionButtons() {
setShowActionButtons({
shown: false
});
}
return ( <div ref={containerRef} ></div>
);
}
https://stackoverflow.com/questions/70665582
复制相似问题