我正在制作 Reddit 克隆版,我正在使用 Next.js,以便在服务器端呈现。我一开始并没有使用 Next.js,当我了解到它后,我立即切换到它。
我创建了一个自定义的 _app.js
,因此页眉和侧边栏存在于每个页面上,并作为最顶层的组件来保存应用程序状态。后者不太奏效。
这是 .project/src/pages/_app.js
:
import App, { Container } from 'next/app';
// Components
import Header from '../components/Header/Header';
const MainLayout = props => (
<React.Fragment>
<Header
isSidebarOpen={props.isSidebarOpen}
sidebarToggle={props.sidebarToggle}
/>
{props.children}
</React.Fragment>
);
export default class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
return { pageProps };
}
state = {
isSidebarOpen: true
};
sidebarToggle = () => {
this.setState({ isSidebarOpen: !this.state.isSidebarOpen });
};
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<MainLayout
isSidebarOpen={this.state.isSidebarOpen}
sidebarToggle={this.sidebarToggle}
>
<Component {...pageProps} />
</MainLayout>
</Container>
);
}
}
我遇到的问题是,isSidebarOpen
和 sidebarToggle
被传递到我需要它们的地方——它们出现在控制台中——但 onClick 处理程序没有't 激活,如果我更改 isSidebarOpen
,它不会生效,直到我重新启动服务器。我在使用 Next.js 之前使用了这种方法,它按预期工作。
我怎样才能实现我想要做的事情?我已经阅读了文档,搜索了 Google 和 Stack Overflow。我什至在没有运气的情况下检查了他们 repo 的问题。我怀疑它与自定义 _app.js
有关,因为 Prop 已正确传递。
最佳答案
一种可能是在您正在使用的组件中定义您的 sidebarToggle
函数。(也许因为在组件内部调用它,代码可能在 _app.js 而不是您的组件中运行,这是一个很大的问题也许吧!但值得一试)
此处 _app.js
是您应用程序的包装器,我认为它不适合在最顶层组件中使用以保持状态。最好让一个简单的 react 根组件来做到这一点!
关于javascript - 使用 Next.js react onClick 事件处理程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543267/