【发布时间】:2019-11-23 05:25:57
【问题描述】:
我有一个非常简单的网站,网站的主体应该滚动,这样地址栏就不再可见了。从this 主题看来,只需调用以下内容就可以解决问题:
window.scrollTo(0,1)
但是在我的 react 应用程序中这根本不起作用,该应用程序是:
import * as React from 'react';
import {Route, Router} from 'react-router';
class App extends React.Component<PropTy> {
componentDidMount() {
console.log('ok');
window.scrollTo(0, 1);
}
render() {
return (<div style={{height: '100vh', position: 'relative'}}>
text
</div>);
}
}
export default App;
我可以手动向下滚动(在移动设备上)。但是它不会自动执行此操作 - 但我确实在控制台中看到“ok”。
index.html 和 manifest.json 与默认的 create-react-app 几乎没有变化:
<!DOCTYPE html>
<!--suppress HtmlUnknownTarget -->
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#7B0000">
<meta name="Description" content="Spots platform, event calendar, enroll">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<title>AllSports</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root" ></div>
</body>
</html>
是什么导致浏览器忽略scrollTo() - 我尝试了不同的滚动偏移量,但它们似乎都不起作用?
我也试过修改 index.html:
<!DOCTYPE html>
<!--suppress HtmlUnknownTarget -->
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#7B0000">
<meta name="Description" content="Spots platform, event calendar, enroll">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<title>AllSports</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root" style="height: 100vh; position: relative;"></div>
</body>
</html>
但这似乎也不起作用。
我现在注意到(感谢您的评论)这是由于反应路由器导入造成的。如果我删除它“工作”的导入。 - 然而,该应用程序与 react-router 紧密耦合,那么我将如何“修复”这个?
【问题讨论】:
-
你不会碰巧在这个应用程序中使用
react-router吧? -
@SébastienRenauld 我是,但我不明白这有什么影响? (在测试中我什至没有“使用”它,只是导入它)
-
类似的事情和它有一些乐趣,特别是在实现类似滚动到顶部的功能时。
-
您在使用
react-router时找到解决方案了吗? -
@John 我实际上发现解决方案是“什么都不做”。无论我做什么,地址栏都会在输入菜单获得焦点时出现。即使我手动向下滚动。因此,
window.scrollTo(0, 1)的解决方案不起作用。 -- 因为我们应用程序中的搜索栏总是获得焦点;
标签: javascript reactjs mobile