Next.js - 基于路由的模态

Nir*_*air 4 reactjs next.js

使用 Next.js 时,我想在另一个页面的顶部显示基于 url 的模式。

如果gallery.js是页面组件,我想/gallery/image/1232132在图库页面的顶部显示带有图像的模式。

那可能吗?

For*_*man 5

如果我正确理解您的问题,您想添加指向各个画廊项目的深层链接。这是可能的,但您需要一个自定义服务器来处理自定义路由。

您需要做的第一件事是设置路由。我在这里分享了一个例子:使用 React router 和 Next JS route

const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());

routes
    .add('gallery', '/gallery')
    .add('gallery-item', '/gallery/image/:image', 'gallery')
Run Code Online (Sandbox Code Playgroud)

然后就可以在getInitialProps方法中访问这个参数,如果设置了image参数就渲染modal:

import React from 'react';
import PropTypes from 'prop-types';

export default class Gallery extends React.Component {
    static propTypes = {
        image: PropTypes.string
    };
    
    static getInitialProps({query: {image}}) {
        return {image};
    }

    render() {
        const {image} = this.props;

        return (
            <div>
                {image &&
                    // render modal
                }
                // render gallery
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)


Cra*_*zit 5

这个问题有点老了,但自 2020 年 3 月以来,官方 Next.js 存储库中有一个完整的示例(您可能应该使用它,因为它必须是维护者的“推荐方式”):

https://github.com/vercel/next.js/tree/canary/examples/with-route-as-modal

这是原始问题:

https://github.com/vercel/next.js/issues/8023

以及相关的公关:

https://github.com/vercel/next.js/pull/11473

  • 好的,但是这个示例为您提供了动态 url 或当前页面顶部的模式。它没有显示如何在当前页面顶部有一个在刷新时持续存在的模式 (3认同)