使用 React 渲染可移植文本
Render Portable Text with React.
Migrating from @sanity/block-content-to-react? Refer to the migration docs.
npm install --save @portabletext/reactimport {PortableText} from '@portabletext/react'
`` renders in both worlds without configuration: use it directly in a React Server Component, or in a file with a 'use client' directive. The package publishes two builds selected automatically through export conditions — client components and SSR load a build optimized with React Compiler, while server components load an uncompiled build through the react-server condition (React Compiler output can't load in server components, and since server components render exactly once, memoization couldn't pay off there anyway).
The rendered HTML does not have any styling applied, so you will either render a parent container with a class name you can target in your CSS, or pass custom components if you want to control the direct markup and CSS of each element.
Default components are provided for all standard features of the Portable Text spec, with logical HTML defaults. You can pass an object of components to use, both to override the defaults and to provide components for your custom content types.
Provided components will be merged with the defaults. In other words, you only need to provide the things you want to override.
Note: Make sure the object does not change on every render - eg do not create the object within a React component, or if you do, use useMemo to ensure referential identity between renders for better performance.
const myPortableTextComponents = {
types: {
image: ({value}) => ,
callToAction: ({value, isInline}) =>
isInline ? (
{value.text}
) : (
),
},
marks: {
link: ({children, value}) => {
const rel = !value.href.startsWith('/') ? 'noreferrer noopener' : undefined
return (
{children}
)
},
},
}
const YourComponent = (props) => {
return
}These are the overridable/implementable keys:
typesAn object of React components that renders different types of objects that might appear both as part of the input array, or as inline objects within text blocks - eg alongside text spans.
Use the isInline property to check whether or not this is an inline object or a block.
The object has the shape {typeName: ReactComponent}, where typeName is the value set in individual _type attributes.
Example of rendering a custom image object:
import {PortableText} from '@portabletext/react'
import urlBuilder from '@sanity/image-url'
import {getImageDimensions} from '@sanity/asset-utils'
// Barebones lazy-loaded image component
const SampleImageComponent = ({value, isInline}) => {
const {width, height} = getImageDimensions(value)
return (
)
}
const components = {
types: {
image: SampleImageComponent,
// Any other custom types you have in your content
// Examples: mapLocation, contactForm, code, featuredProjects, latestNews, etc.
},
}
const YourComponent = (props) => {
return
}marksObject of React components that renders different types of marks that might appear in spans. Marks can either be simple "decorators" (eg emphasis, underline, italic) or full "annotations" which include associated data (eg links, references, descriptions).
If the mark is a decorator, the component will receive a markType prop which has the name of the decorator (eg em). If the mark is an annotation, it will receive both a markType with the associated _type property (eg link), and a value property with an object holding the data for this mark.
The component also receives a children prop that should (usually) be returned in whatever parent container component makes sense for this mark (eg , ).
// `components` object you'll pass to PortableText w/ optional TS definition
import {PortableTextComponents} from '@portabletext/react'
const components = {
marks: {
// Ex. 1: custom renderer for the em / italics decorator
em: ({children}) => {children},
// Ex. 2: rendering a custom `link` annotation
link: ({value, children}) => {
const target = (value?.href || '').startsWith('http') ? '_blank' : undefined
return (
{children}
)
},
},
} satisfies PortableTextComponentsblockAn object of React components that renders portable text blocks with different style properties. The object has the shape {styleName: ReactComponent}, where styleName is the value set in individual style attributes on blocks (normal being the default).
import {PortableText, PortableTextReactComponents} from '@portabletext/react'
// `components` object you'll pass to PortableText
const components = {
block: {
// Ex. 1: customizing common block types
normal: ({children}) =>
{children}
,
h1: ({children}) =>
{children}
,
blockquote: ({children}) =>
{children}
,
// Ex. 2: rendering custom styles
customHeading: ({children}) => (
{children}
),
},
} satisfies PartialThe block object can also be set to a single React component, which would handle block styles of any type.
listObject of React components used to render lists of different types (bullet vs number, for instance, which by default is and , respectively).
Note that there is no actual "list" node type in the Portable Text specification, but a series of list item blocks with the same level and listItem properties will be grouped into a virtual one inside of this library.
const components = {
list: {
// Ex. 1: customizing common list types
bullet: ({children}) =>
{children}
,
number: ({children}) =>
{children}
,
// Ex. 2: rendering custom lists
checkmarks: ({children}) =>
{children}
,
},
}The list property can also be set to a single React component, which would handle lists of any type.
listItemObject of React components used to render different list item styles. The object has the shape {listItemType: ReactComponent}, where listItemType is the value set in individual listItem attributes on blocks.
const components = {
listItem: {
// Ex. 1: customizing common list types
bullet: ({children}) =>
{children}
,
// Ex. 2: rendering custom list items
checkmarks: ({children}) =>
✅ {children}
,
},
}The listItem property can also be set to a single React component, which would handle list items of any type.
hardBreakComponent to use for rendering "hard breaks", eg \n inside of text spans.
Will by default render a . Pass false to render as-is (\n)
unknownMarkReact component used when encountering a mark type there is no registered component for in the components.marks prop.
unknownTypeReact component used when encountering an object type there is no registered component for in the components.types prop.
unknownBlockStyleReact component used when encountering a block style there is no registered component for in the components.block prop. Only used if components.block is an object.
unknownListReact component used when encountering a list style there is no registered component for in the components.list prop. Only used if components.list is an object.
unknownListItemReact component used when encountering a list item style there is no registered component for in the components.listItem prop. Only used if components.listItem is an object.
When the library encounters a block, mark, list or list item with a type that is not known (eg it has no corresponding component in the components property), it will by default print a console warning.
To disable this behavior, you can either pass false to the onMissingComponent property, or give it a custom function you want to use to report the error. For instance:
import {PortableText} from '@portabletext/react'
// or, pass it a function:
{
myErrorLogger.report(message, {
// eg `someUnknownType`
type: options.type,
// 'block' | 'mark' | 'blockStyle' | 'listStyle' | 'listItemStyle'
nodeType: options.nodeType
})
}}
/>This module also exports a function (toPlainText()) that will render one or more Portable Text blocks as plain text. This is helpful in cases where formatted text is not supported, or you need to process the raw text value.
For instance, to render an OpenGraph meta description for a page:
import {toPlainText} from '@portabletext/react'
const MetaDescription = (myPortableTextData) => {
return
}Or to generate element IDs for headers, in order for them to be linkable:
import {PortableText, toPlainText, PortableTextComponents} from '@portabletext/react'
import slugify from 'slugify'
const LinkableHeader = ({children, value}) => {
// `value` is the single Portable Text block of this header
const slug = slugify(toPlainText(value))
return
{children}
}
const components = {
block: {
h2: LinkableHeader,
},
} satisfies PortableTextComponentsWhen you use Sanity TypeGen, @portabletext/react infers everything for you - which custom types, marks, block styles, and list styles your handlers receive, and what shape their value props have - directly from your queries. No manual generics or hand-written type unions needed.
The library exposes three utility types to make this ergonomic:
InferValue - derives a Portable Text array value type from any TypeGen query result type.InferComponents - forgiving component map type, mirrors the inline components prop inference.InferStrictComponents - strict component map type, requires inferred handlers and rejects unknown ones.CustomPortableText componentThis is the recommended pattern for a single Portable Text renderer that you reuse across your app. InferValue collects every Portable Text item shape returned by every registered TypeGen query into an array value type, and InferStrictComponents forces you to define a handler for each of them.
…You can drop this component in anyw
暂无开放 Issues,或尚未同步最近议题。