React Component Preview Markdown Teks di browser web. Jumlah minimal CSS untuk mereplikasi gaya penurunan harga GitHub. Situs web dokumen saat ini dikonversi menggunakan komponen React ini.
@v4$ npm install @uiw/react-markdown-preview --save import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `
## MarkdownPreview
> todo: React component preview markdown text.
` ;
export default function Demo ( ) {
return (
< MarkdownPreview source = { source } style = { { padding : 16 } } />
)
} import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `
## MarkdownPreview
## Header 2
### Header 3
` ;
export default function Demo ( ) {
return (
< MarkdownPreview
source = { source }
style = { { padding : 16 } }
rehypeRewrite = { ( node , index , parent ) => {
if ( node . tagName === "a" && parent && / ^h(1|2|3|4|5|6) / . test ( parent . tagName ) ) {
parent . children = parent . children . slice ( 1 )
}
} }
/>
) ;
} Sintaks: ```jsx {1,4-5}
import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `
```js {2}
function () {
console.log('hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello')
}
```
```js {2}
function () {
console.log('hello ')
}
```
` ;
export default function Demo ( ) {
return (
< MarkdownPreview
source = { source }
style = { { padding : 16 } }
rehypeRewrite = { ( node , index , parent ) => {
if ( node . tagName === "a" && parent && / ^h(1|2|3|4|5|6) / . test ( parent . tagName ) ) {
parent . children = parent . children . slice ( 1 )
}
} }
/>
) ;
} Sintaks: ```jsx showLineNumbers {1,4-5}
import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `
```js showLineNumbers
function () {
console.log('hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello')
}
```
```js showLineNumbers {2}
function () {
console.log('hello ')
}
```
` ;
export default function Demo ( ) {
return (
< MarkdownPreview
source = { source }
style = { { padding : 16 } }
rehypeRewrite = { ( node , index , parent ) => {
if ( node . tagName === "a" && parent && / ^h(1|2|3|4|5|6) / . test ( parent . tagName ) ) {
parent . children = parent . children . slice ( 1 )
}
} }
/>
) ;
} import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `
```js
function () {
console.log('hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello')
}
```
```js
function () {
console.log('hello ')
}
```
` ;
export default function Demo ( ) {
return (
< MarkdownPreview source = { source } style = { { padding : 16 } } />
) ;
} Contoh berikut dapat membantu Anda mengecualikan kode penyorotan kode dari dimasukkan dalam bundel. @uiw/react-markdown-preview/nohighlight Component tidak mengandung paket penyorotan kode rehype-prism-plus , showLineNumbers dan fungsi highlight line tidak akan lagi berfungsi. (#586)
import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview/nohighlight' ;
const source = `
```js
function () {
console.log('hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello')
}
```
```js
function () {
console.log('hello ')
}
```
` ;
export default function Demo ( ) {
return (
< MarkdownPreview
source = { source }
style = { { padding : 16 } }
rehypeRewrite = { ( node , index , parent ) => {
if ( node . tagName === "a" && parent && / ^h(1|2|3|4|5|6) / . test ( parent . tagName ) ) {
parent . children = parent . children . slice ( 1 )
}
} }
/>
) ;
} Abaikan tampilan konten melalui komentar HTML, ditampilkan di Github ReadMe, dikecualikan dalam HTML.
import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `
<!--rehype:ignore:start-->
Content ignored
<!--rehype:ignore:end-->
Some content is ignored, please check the source code
` ;
export default function Demo ( ) {
return (
< MarkdownPreview
source = { source }
style = { { padding : 16 } }
rehypeRewrite = { ( node , index , parent ) => {
if ( node . tagName === "a" && parent && / ^h(1|2|3|4|5|6) / . test ( parent . tagName ) ) {
parent . children = parent . children . slice ( 1 )
}
} }
/>
) ;
} <!-- rehype:ignore:start --> Ignored content <!-- rehype:ignore:end --> Katex adalah perpustakaan JavaScript yang cepat dan mudah digunakan untuk rendering matematika Tex di web, kami melakukan rendering matematika melalui KaTeX .
npm install katex import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
import { getCodeString } from 'rehype-rewrite' ;
import katex from 'katex' ;
import 'katex/dist/katex.css' ;
const source = `This is to display the
`$$c = \pm\sqrt{a^2 + b^2}$$`
in one line
```KaTeX
c = \pm\sqrt{a^2 + b^2}
```
` ;
export default function Demo ( ) {
const [ value , setValue ] = React . useState ( source ) ;
return (
< MarkdownPreview
source = { source }
style = { { padding : 16 } }
components = { {
code : ( { children = [ ] , className , ... props } ) => {
if ( typeof children === 'string' && / ^$$(.*)$$ / . test ( children ) ) {
const html = katex . renderToString ( children . replace ( / ^$$(.*)$$ / , '$1' ) , {
throwOnError : false ,
} ) ;
return < code dangerouslySetInnerHTML = { { __html : html } } style = { { background : 'transparent' } } /> ;
}
const code = props . node && props . node . children ? getCodeString ( props . node . children ) : children ;
if (
typeof code === 'string' &&
typeof className === 'string' &&
/ ^language-katex / . test ( className . toLocaleLowerCase ( ) )
) {
const html = katex . renderToString ( code , {
throwOnError : false ,
} ) ;
return < code style = { { fontSize : '150%' } } dangerouslySetInnerHTML = { { __html : html } } /> ;
}
return < code className = { String ( className ) } > { children } </ code > ;
} ,
} }
/>
) ;
} Menggunakan putri duyung untuk menghasilkan diagram dan diagram alur dari teks dengan cara yang sama seperti penurunan harga
import React , { useState , useRef , useEffect , Fragment , useCallback } from "react" ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
import { getCodeString } from 'rehype-rewrite' ;
import mermaid from "mermaid" ;
const randomid = ( ) => parseInt ( String ( Math . random ( ) * 1e15 ) , 10 ) . toString ( 36 ) ;
const Code = ( { inline , children = [ ] , className , ... props } ) => {
const demoid = useRef ( `dome ${ randomid ( ) } ` ) ;
const [ container , setContainer ] = useState ( null ) ;
const isMermaid = className && / ^language-mermaid / . test ( className . toLocaleLowerCase ( ) ) ;
const code = props . node && props . node . children ? getCodeString ( props . node . children ) : children [ 0 ] || '' ;
const reRender = async ( ) => {
if ( container && isMermaid ) {
try {
const str = await mermaid . render ( demoid . current , code ) ;
container . innerHTML = str . svg ;
} catch ( error ) {
container . innerHTML = error ;
}
}
}
useEffect ( ( ) => {
reRender ( )
} , [ container , isMermaid , code , demoid ] ) ;
const refElement = useCallback ( ( node ) => {
if ( node !== null ) {
setContainer ( node ) ;
}
} , [ ] ) ;
if ( isMermaid ) {
return (
< Fragment >
< code id = { demoid . current } style = { { display : "none" } } />
< code ref = { refElement } data-name = "mermaid" />
</ Fragment >
) ;
}
return < code > { children } </ code > ;
} ;
const source = `The following are some examples of the diagrams, charts and graphs that can be made using Mermaid and the Markdown-inspired text specific to it.
```mermaid
graph TD
A[Hard] -->|Text| B(Round)
B --> C{Decision}
C -->|One| D[Result 1]
C -->|Two| E[Result 2]
```
```mermaid
sequenceDiagram
Alice->>John: Hello John, how are you?
loop Healthcheck
John->>John: Fight against hypochondria
end
Note right of John: Rational thoughts!
John-->>Alice: Great!
John->>Bob: How about you?
Bob-->>John: Jolly good!
```
` ;
// const source = `
// ```mermaid
// graph TD;
// A-->B;
// A-->C;
// B-->D;
// C-->D;
// ```
// `;
export default function Demo ( ) {
return (
< MarkdownPreview
source = { source }
style = { { padding : 16 } }
components = { {
code : Code
} }
/>
) ;
} Harap dicatat bahwa Markdown perlu disanitasi jika Anda tidak sepenuhnya mempercayai penulis Anda. Jika tidak, aplikasi Anda rentan terhadap XSS. Ini dapat dicapai dengan menambahkan rehype-sanitize sebagai plugin.
import React from 'react' ;
import rehypeSanitize from "rehype-sanitize" ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `
## MarkdownPreview
**Hello world!!!** <IFRAME SRC="javascript:javascript:alert(window.origin);"></IFRAME>
<!-- test --> 123
<!-- test --> 456 <!-- test -->
` ;
const rehypePlugins = [ rehypeSanitize ] ;
export default function Demo ( ) {
return (
< MarkdownPreview source = { source } rehypePlugins = { rehypePlugins } style = { { padding : 16 } } />
)
} import { ReactMarkdownProps } from 'react-markdown' ;
import { RehypeRewriteOptions } from 'rehype-rewrite' ;
type MarkdownPreviewProps = {
prefixCls ?: string ;
className ?: string ;
source ?: string ;
disableCopy ?: boolean ;
style ?: React . CSSProperties ;
pluginsFilter ?: ( type : 'rehype' | 'remark' , plugin : PluggableList ) => PluggableList ;
wrapperElement ?: React . DetailedHTMLProps < React . HTMLAttributes < HTMLDivElement > , HTMLDivElement > & {
'data-color-mode' ?: 'light' | 'dark' ;
} ;
onScroll ?: ( e : React . UIEvent < HTMLDivElement > ) => void ;
onMouseOver ?: ( e : React . MouseEvent < HTMLDivElement > ) => void ;
rehypeRewrite ?: RehypeRewriteOptions [ 'rewrite' ] ;
} & ReactMarkdownProps ;source ( string , default: '' )className ( string? )div dengan Nama Kelas ini Detail ReactMarkdownProps ini. Tingkatkan react-markdown v9
children ( string , default: '' )className ( string? )div dengan Nama Kelas iniskipHtml ( boolean , default:falsetrue )allowElement ( (element, index, parent) => boolean? Opsional)allowedElements / disallowedElements digunakan terlebih dahulu!remarkPlugins ( Array.<Plugin> , default: [] )rehypePlugins ( Array.<Plugin> , default: [] )Catatan
Tingkatkan react-markdown v8 ke v9
urlTransform transformImageUri dan transformLinkUri dihapus. Memiliki dua fungsi sedikit banyak, terutama karena ada lebih banyak URL yang mungkin ingin Anda ubah (atau yang mungkin tidak aman sehingga kami membuatnya aman). Dan nama dan API mereka agak aneh. Anda dapat menggunakan prop urlTransform baru sebagai gantinya untuk mengubah semua URL Anda.
linkTarget Opsi linkTarget telah dihapus; Anda mungkin tidak akan menetapkan target. Jika Anda mau, gunakan rehype-external-links .
includeElementIndex Opsi includeElementIndex telah dihapus, jadi index tidak pernah diteruskan ke komponen. Tulis plugin untuk lulus index :
import { visit } from 'unist-util-visit'
function rehypePluginAddingIndex ( ) {
/**
* @param {import('hast').Root} tree
* @returns {undefined}
*/
return function ( tree ) {
visit ( tree , function ( node , index ) {
if ( node . type === 'element' && typeof index === 'number' ) {
node . properties . index = index
}
} )
}
}rawSourcePos Raws Opsi rawSourcePos telah dihapus, sehingga sourcePos tidak pernah diteruskan ke komponen. Semua komponen dilewati node , sehingga Anda bisa mendapatkan node.position dari mereka.
sourcePos Opsi sourcePos telah dihapus, sehingga data-sourcepos tidak pernah diteruskan ke elemen. Tulis plugin untuk lulus index :
import { stringifyPosition } from 'unist-util-stringify-position'
import { visit } from 'unist-util-visit'
function rehypePluginAddingIndex ( ) {
/**
* @param {import('hast').Root} tree
* @returns {undefined}
*/
return function ( tree ) {
visit ( tree , function ( node ) {
if ( node . type === 'element' ) {
node . properties . dataSourcepos = stringifyPosition ( node . position )
}
} )
}
}Saat mengamati komponen, alat peraga ini tidak lagi disahkan:
inline pada code - Buat plugin atau gunakan pre untuk bloklevel pada h1 , h2 , h3 , h4 , h5 , h6 - Periksa node.tagName Sebaliknyachecked ON li -Periksa kelas task-list-item atau periksa props.childrenindex di li - Buat pluginordered di li - Buat plugin atau periksa orang tuadepth ol , ul - Buat pluginordered di ol , ul - periksa node.tagName sebagai gantinyaisHeader di td , th - periksa node.tagName SebaliknyaisHeader di tr - Buat plugin atau periksa anak -anak Gunakan komentar HTML <!--rehype:xxx--> untuk membiarkan kustomisasi gaya dukungan Markdown.
## Title
<!-- rehype:style=display: flex; height: 230px; align-items: center; justify-content: center; font-size: 38px; -->
Markdown Supports ** Style ** <!-- rehype:style=color: red; -->Here is a simple footnote [ ^ 1 ] . With some additional text after it.
[ ^ 1 ] : My reference. # Hello World
<!-- rehype:ignore:start --> Hello World <!-- rehype:ignore:end -->
Good!Keluaran:
< h1 > Hello World </ h1 >
< p > Good! </ p > import React from 'react' ;
import MarkdownPreview from '@uiw/react-markdown-preview' ;
const source = `>
>
> [!NOTE]
> Useful information that users should know, even when skimming content.
> [!TIP]
> Helpful advice for doing things better or more easily.
> [!IMPORTANT]
> Key information users need to know to achieve their goal.
> [!WARNING]
> Urgent info that needs immediate user attention to avoid problems.
> [!CAUTION]
> Advises about risks or negative outcomes of certain actions.
` ;
export default function Demo ( ) {
return (
< MarkdownPreview source = { source } style = { { padding : 16 } } />
)
} Secara default, dark-mode secara otomatis diaktifkan sesuai dengan sistem. Jika Anda perlu beralih secara manual, cukup atur parameter data-color-mode="dark" untuk tubuh.
< html data-color-mode =" dark " > document . documentElement . setAttribute ( 'data-color-mode' , 'dark' )
document . documentElement . setAttribute ( 'data-color-mode' , 'light' ) Mewarisi variabel warna khusus dengan menambahkan pemilih .wmde-markdown-var .
const Demo = ( ) => {
return (
< div >
< div className = "wmde-markdown-var" > </ div >
< MarkdownPreview source = "Hello World!" />
</ div >
)
} Atur tema light .
<MarkdownPreview
source="Hello World!"
wrapperElement={{
+ "data-color-mode": "light"
}}
/>Menjalankan proyek dalam mode pengembangan.
# Step 1, run first,
# listen to the component compile and output the .js file
# listen for compilation output type .d.ts file
# listen to the component compile and output the .css file
npm run start
# Step 2, development mode, listen to compile preview website instance
npm run docMembangun aplikasi untuk produksi ke folder build.
npm run buildBangunan diminifikasi dan nama file termasuk hash. Aplikasi Anda siap digunakan!
Jika Anda membutuhkan lebih banyak editor penurunan harga yang kaya fitur, Anda dapat menggunakan editor @uiwjs/react-markdown-editor
Seperti biasa, terima kasih kepada kontributor kami yang luar biasa!
Dibuat dengan kontributor aksi.
Berlisensi di bawah lisensi MIT.