NextJS中的持久焦点



我正在建立我的第一个NextJS网站,并遇到了一些奇怪的行为。

我的网站标题只是一些<Link />组件链接到我的网站的各个页面。这些链接使用:focus选择器在CSS中应用了简单的焦点样式。

当您单击其中一个链接时,焦点样式按预期应用,站点导航到新的URL,但是,即使在新页面加载后,焦点样式仍然存在。

是否有一种方法可以在过渡到新页面时删除焦点状态?

希望有人可以帮助NextJS新手。谢谢。

我设法解决了这个问题,所以将来如果有人遇到类似的问题,我会在这里发布。

我的头链接在我的自定义_app.js文件中,该文件不会重新渲染,因此焦点状态持续存在。解决方案是将我的站点模板移出_app.js,并将其放在它自己的组件中,然后包装每个页面。

页面/_app.js

const App = ({ Component, pageProps }) => <Component {...pageProps} />;
export default App;

组件/SiteLayout.js

import Head from "next/head";
const SiteLayout = ({ children }) => {
return (
<>
<Head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="mobile-web-app-capable" content="yes" />
</Head>
<header>
<Link href="my-page">
<a>My page</a>
</Link>
</header>
<main role="main">
{children}
</main>
</>
);
};
export default SiteLayout;

页面/my-page.js

import SiteLayout from "components/SiteLayout";
const MyPage = () => (
<SiteLayout>
<h1>My Page</h1>
</SiteLayout>
);
export default MyPage;

我认为这是可行的。设置一个高度和宽度为0的输入,并在更改url时关注它。

import { withRouter } from 'next/router';
import React, { createRef, Component } from 'react';
class MyComponent extends Component {
componentDidUpdate(prevProps) {
if (this.props.router != prevProps.router) {
this.input_ref.focus();
}
}
input_ref = createRef()
render() {
return (
<>
{/* ... */}
<input ref={this.input_ref} style={{width: 0, height: 0}} />
{/* ... */}
</>
)
}
}
export default withRouter(MyComponent);

最新更新