gpt4 book ai didi

next.js - 设置 Storybook 以使用 Next.js 的 Link 标签

转载 作者:行者123 更新时间:2023-12-03 14:23:41 24 4
gpt4 key购买 nike

我正在尝试为 Next.js 项目设置 Storybook。我有一个渲染 Link 的组件来自 Next.js 的标签。我的问题是,当我加载这个组件时,Storybook 会抛出以下错误:

Cannot read property 'pageLoader' of null
at Link.handleRef

要让 Storybook 与 Next.js Routing 一起工作,需要做什么,特别是渲染 Link标签?

更新:导致错误的代码:

// button-component.js
import Link from 'next/link.js';
import t from 'prop-types';
import React from 'react';

function Button({ as, children, href, ...props }) {
const isExternal = href && href.startsWith('http');
const a = (
<a href={href} {...props}>
{children}
</a>
);

if (href) {
return isExternal ? (
a
) : (
<Link href={href} as={as}>
{a}
</Link>
);
}

return (
<button type="button" {...props}>
{children}
</button>
);
}

Button.propTypes = {
as: t.string,
children: t.node,
href: t.string,
};

export default React.memo(Button);

// button.stories.js
import React from 'react';

import Button from './button-component';

export default {
title: 'Button',
};

export const standardButton = () => <Button>Standard Button</Button>;

export const internalLink = () => <Button href='/buy'>
Internal Link
</Button>;

export const externalLink = () => (
<Button target="_blank" href="https://www.hopin.to">
External Link
</Button>
);

最佳答案

我在 Next.js 的 github 上发现了一个关于此问题的报告:https://github.com/zeit/next.js/issues/9951

它仅在 5 天前报告,因此您可能遇到相同的问题。解决方法是升级nextjs v9.1.8-canary.6 .阅读有关此内容的更多信息并查看源代码,这可能是您的问题。此外,如果您想尝试更新的东西,还有更多最近的 nextjs 金丝雀版本。

如果这不能解决它,我的另一个猜测是您收到错误是因为您使用的是 Link在 Next.js 页面之外。 Next.js 可能在幕后包含页面的依赖项。 Link可能依赖于这些依赖项,并在找不到它们时抛出错误。如果你想在 Next.js 页面之外测试你的组件,你可以创建一个自定义 Link测试您是否在 Next.js 中并且仅呈现 Link 的组件如果你是。例如:

import Link from 'next/link'
import Router from 'next/router'

const CustomLink = ({children, ...otherProps}) => {
const isPage = () => {
// if we're in a next.js route, then Router.router will be set
return Boolean(Router.router)
}

return isPage()
? (<Link {...otherProps}>{children}</Link>)
: children
}

然后使用 CustomLink而不是 Link .

关于next.js - 设置 Storybook 以使用 Next.js 的 Link 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59712474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com