reactjs - 在没有 MDX 的 Markdown 中插入一个 React 组件
问题描述
如何<MyReactComponent />
在降价段落中插入?
- 我需要它是通用的——也就是说,markdown 可能被一个非反应感知程序解析,在这种情况下它应该被忽略。
- react 组件不需要参数(我不需要向它传递数据,只需要在 markdown 中指明它的去向)
我正在将 NextJS 与来自无头 CMS 的数据一起使用,如下所示:
import marked from 'marked';
import MyReactComponent from './myComponent';
function Content({markdownContent}){
return(
<div className="content">
<div dangerouslySetInnerHTML={{ __html: marked(markdownContent) }} />;
// squirt MyReactComponent into appropriate place above...
</div>
)
}
我故意使用“标记”库,因为它轻巧且基本......我不想使用像 mdx 这样重的东西,或者复杂的......我只需要在降价中替换某种类型的占位符。
解决方案
如果你的 markdown 中有一个带有唯一标识符的元素,你可以设置一个useEffect
钩子来更新 dom 。ReactDOM.render
这是一个概念证明:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import marked from "marked";
const MyComponent = () => <span>⭐</span>;
const markdownContent = `
# MyComponent
Testing
`;
function App() {
const [initialized, setInitialized] = useState(false);
useEffect(() => {
const el = document.getElementById("mycomponent");
if (el) {
ReactDOM.render(<MyComponent />, el); // you can pass props as usual
}
setInitialized(true);
}, []);
return (
<div
style={{ opacity: initialized ? 1 : 0 }}
dangerouslySetInnerHTML={{ __html: marked(markdownContent) }}
/>
);
}
默认情况下,marked
在发出标题时将包含一个 id 属性。这就是为什么我使用标题作为 React 组件的占位符。诀窍是知道如何marked
生成 ID。
你可以玩这个 CodeSandbox:
推荐阅读
- node.js - 在 WebRTC SDP 中禁用回声消除
- google-bigquery - 在 BigQuery 中按组计算百分位数
- flutter - 我想从异步方法中获取数据作为字符串,但我得到了未来的实例
- github - 推送到 git hub 时不断出错。有人可以帮我吗
- reactjs - 使用 LocalStorage 和 DB 反应状态无限循环
- terraform - “v”参数的值无效:无法将“”转换为数字;给定字符串 terraform eks 模块
- python - 迭代不同长度列表中的所有列表
- javascript - Javascript按钮删除整个表,应该只删除它创建的行
- android - 为什么每当我生成一个已签名的 APK 时都会收到重复输入错误?
- kotlin-multiplatform - 在 SQLDelight 中插入数据时没有这样的表