【问题标题】:NextJS: Render Markdown with tableNextJS:使用表格渲染 Markdown
【发布时间】:2021-08-17 09:07:35
【问题描述】:

在我的 Nextjs 项目中,我通过 API 接收到一些降价,我需要在 Nextjs 页面中显示它。

我的代码如下:

import React from "react"
import { GetServerSideProps } from "next"
import ReactMarkdown from "react-markdown"
import gfm from 'remark-gfm'
import Layout from "../../components/Layout"
import { PostProps } from "../../components/Post"
import { server } from '../../config';

const fetchSinglePostServer = async (id) => {
  const res = await fetch(server + '/api/post/' + id);
  return res.json();
}


export const getServerSideProps: GetServerSideProps = async ({ params }) => {

  const post = await fetchSinglePostServer(params.id);
    return {
      props: post,
    };
};

const Post: React.FC<PostProps> = (props) => {
  let title = props.title

return (
    <Layout title={title}>
      <main className="container mx-auto mt-6 px-2 dark:bg-gray-800">
        <div className="flex md:space-x-4 justify-center">
          <div className="mb-4">
            <h2 className="text-2xl font-bold my-2">{title}</h2>
              <p className="mb-2">By {props?.author?.name || "Unknown author"}</p>
              <div className="prose lg:prose-lg">
                <ReactMarkdown remarkPlugins={[gfm]}>{props.markdown}</ReactMarkdown>
              </div>
          </div>
        </div>
      </main>
    </Layout>
  )
}

export default Post

整个代码在没有remarkPlugins={[gfm]} 的情况下运行良好。

但是,我的 markdown 包含一个表格,要显示该表格,我需要使用这个插件。

使用此插件会破坏页面。我收到Server Error TypeError: Cannot read property '2' of undefined

当markdown也包含表格时,我正在寻找在我的nextjs页面中显示这个api-received markdown内容的解决方案。

我的示例标记:

This is an example post, with a [link](https://nextjs.org) and a React component:
  
  The title and description are pulled from the MDX file and processed using gray-matter. Additionally, links are rendered using a custom component passed to next-mdx-remote.
  
  Go back [home](/).
  
  # Table

  | Branch  | Commit           |
  | ------- | ---------------- |
  | main    | 0123456789abcdef |
  | staging | fedcba9876543210 |

【问题讨论】:

  • 您能否提供一个带有您尝试呈现的表格的降价示例?我似乎无法复制这个问题。
  • 我在上面添加了我的示例降价。请注意,它工作得很好。仅当我为表添加插件 remarkPlugins={[gfm]} 时才会出现此问题。

标签: reactjs next.js


【解决方案1】:

我认为编写自己的表格解释器一点也不难。下面我通过html插入来举个例子(比如dangerouslySetInnerHTML),但是如果你稍微重新设计一下功能,你可以做一个完整的组件插入——这是可能的。

const text = `  
  | Branch  | Commit           |
  | ------- | ---------------- |
  | main    | 0123456789abcdef |
  | staging | fedcba9876543210 | 


  | Branch  | Commit           |Comment |
  | ------- | ---------------- | ------ |
  | main    |                  | old    |
  | staging | fedcba9876543210 | new    | 
`

const findTables = (text) => {
  const tables = [];
  let table = null
  let  isTable = false;
  const lines = text.split('\n')
  for (let i = 0; i < lines.length; i++){
    const line = lines[i].trim();
    let row = '';
    if (row = line.match(/^\|(.*)\|$/)) {
      if(!isTable){
        isTable = true
        table = []; // new table
      }
      table.push(row[1].split('|'));
    } else {
      if (isTable) {
        tables.push(table)
      }
      isTable = false;
    }
  }
  return tables
}

// is it | ------- | ---------------- |  ?
const isHeaderBreak = (row) => row
  .reduce((acc, e) => acc &&  !!e.trim()
    .match(/^\-+$/), true)

// <tr><td></td>...</tr>
const makeRow = (rawRow) => {
  const data =  rawRow.reduce((acc, e )=> `${acc}<td>${e.trim()}</td>`, '')
  let row = `<tr>${data}</tr>\n`
  return row;
}

const makeTable = (table) => {
  let header = '';
  let body = '';
  let isHeader = true;
  for (let i = 0; i < table.length; i++){
    if (isHeaderBreak(table[i])) {
      isHeader = false;
      continue;
    }
    if (isHeader) header += makeRow(table[i]);
    else body += makeRow(table[i]); 
  }
  return `<table border="1">
  <thead>
  ${header}<thead>
  <tbody>
  ${body}</tbody>
  </table>
  `
}

const tables = findTables(text);
for (let i = 0; i < tables.length; i++){
  document.write(makeTable(tables[i]))
}
table {
  width: 80%;
  margin: 20px;
}

【讨论】:

  • 谢谢。这很有帮助。
  • 一点也不,我很高兴你没问题。一些程序员不喜欢重新发明轮子。而且我不喜欢使用任何你可以在较小的体积中自己实现的东西来完成所需的任务)。当然,有很多有用的库,只要它们能正常工作,一切都很好。
  • 我刚刚了解了 next-mdx-remote 库,这解决了我的问题。
  • 格栅!无论如何,当问题解决时:)
猜你喜欢
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2021-05-09
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多