[英]Scroll into a div that is hidden initially in react
我在 next.js 中构建了一个 web 聊天应用程序,我有一个表情符号选择器按钮,当它单击时会出现表情符号菜单。问题是,为了让用户看到他必须向下滚动的表情符号菜单。我试过 scrollIntoView () 但它似乎不起作用,可能我做错了什么。
import {Picker} from "emoji-mart";
const pickerRef = useRef()
const[showEmojis,setShowEmojis]=useState(false);
useEffect(() => {
if(showEmojis) {
pickerRef.current.scrollIntoView(true)
}
} , [showEmojis])
return(
<EmoticonContainer >
{showEmojis && (<Picker ref={pickerRef} id="picker" style={{width: '100%'}} onSelect={addEmoji}/>)}
</EmoticonContainer>
)
const EmoticonContainer=styled.div`
display:flex;
flex-direction:column;
`;
我试过这段代码,但它似乎不起作用。它给了我这个错误:TypeError: pickerRef.current.scrollIntoView is not a function
嘿,尝试在选择器下方添加一个 div 并滚动到该 div,因为有时那些第三方库会附带 css 并且您无法覆盖它们
import {Picker} from "emoji-mart";
const pickerRef = useRef()
const[showEmojis,setShowEmojis]=useState(false);
useEffect(() => {
pickerRef.current.scrollIntoView(true)
} , [showEmojis])
return(
<>
<EmoticonContainer >
<Picker id="picker" style={{width: '100%'}} onSelect={addEmoji}/>
</EmoticonContainer>
<div ref={emojiRef}></div>
</>
)
const EmoticonContainer=styled.div`
display:flex;
flex-direction:column;
`;
试试这个,看看它会按照你需要的方式滚动
因为它在开始时是隐藏的,所以pickerRef.current
应该返回 undefined ,这将导致该错误,因为 undefined 没有方法.scrollIntoView
。 要解决此问题,您可以做?.
pickerRef.current?.scrollIntoView()
请参阅: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
可选的链接运算符 (?.) 使您能够读取位于连接对象链深处的属性值,而无需检查链中的每个引用是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.