React Hooks更新导致页面自动滚顶,如何避免该问题?
解决Hook更新时页面自动滚动到顶部的问题
你遇到的问题其实和Hook更新本身无关,罪魁祸首是代码里的<a href="#">标签——点击它会触发浏览器默认的锚点跳转行为,直接回到页面顶部,刚好和Hook更新的时机重合,才让你误以为是Hook导致的滚动。
下面给两种简单的解决办法:
方法一:阻止a标签的默认跳转行为
修改ExpandProduct函数,让它接收事件对象并阻止默认行为:
export default function UserProduct(props) { const [expanded, setExpanded] = React.useState(false); // 添加事件参数 async function ExpandProduct(event) { // 阻止浏览器默认跳转行为 event.preventDefault(); var call = await ProductsTransactionsAPI(props.product.pk, props.product.type); if (call.Success) { setTransactions(call.Data.Transactions); } setExpanded(true); } return ( <div style={{borderBottom: '1px solid #e0e0e0'}}> <div className="user-product" style={{display: 'flex', justifyContent: 'space-between'}}> <div className="user-product-title"> <img src={image} height='75px'/> {props.product.name} </div> {/* 将事件对象传入函数 */} <a href="#" onClick={(e) => ExpandProduct(e)}><ExpandMoreIcon/></a> </div> </div> ) }
方法二:换成语义更合适的button标签
因为这个元素是用来触发展开交互的按钮,不是跳转链接,用<button>替代<a>更符合HTML语义,也不会有默认跳转问题:
export default function UserProduct(props) { const [expanded, setExpanded] = React.useState(false); async function ExpandProduct() { var call = await ProductsTransactionsAPI(props.product.pk, props.product.type); if (call.Success) { setTransactions(call.Data.Transactions); } setExpanded(true); } return ( <div style={{borderBottom: '1px solid #e0e0e0'}}> <div className="user-product" style={{display: 'flex', justifyContent: 'space-between'}}> <div className="user-product-title"> <img src={image} height='75px'/> {props.product.name} </div> {/* 替换成button,可加样式去除默认按钮外观 */} <button onClick={() => ExpandProduct()} style={{border: 'none', background: 'none', cursor: 'pointer'}}> <ExpandMoreIcon/> </button> </div> </div> ) }
两种方法都能解决页面自动滚动到顶部的问题,推荐第二种,既符合语义又能避免额外的事件处理。
内容的提问来源于stack exchange,提问作者Kyle Andrew
相关产品推荐
相关产品推荐

