为Sanity中String类型字段设置动态initialValue
实现Sanity中myPage文档path字段的动态初始值生成
要让path字段根据slug的值自动生成初始值并实时同步,可通过以下修改实现:
修改后的完整代码
import React from "react"; export default { name: "myPage", title: "My Page", type: "document", fields: [ { name: "title", type: "string", title: "Page Title", validation: (Rule) => Rule.required(), }, { name: "slug", type: "slug", title: "Slug", options: { source: "title", maxLength: 200, slugify: (input) => input .slice(0, 200) .toLowerCase() .replace(/\s+/g, "-") .replace(/[&\/\\#,+()$~%.'`’":*?<>{}]/g, ""), }, validation: (Rule) => Rule.required(), }, { name: "path", type: "string", title: "URL Path", readOnly: true, // 基于slug生成初始值 initialValue: ({ document }) => { return document?.slug?.current ? `/blog/events/${document.slug.current}` : ""; }, // 监听slug变化,实时更新path components: { input: (props) => { const { document, onChange, value } = props; React.useEffect(() => { if (document?.slug?.current) { const newPath = `/blog/events/${document.slug.current}`; if (newPath !== value) { onChange([{ patch: { set: { path: newPath } } }]); } } }, [document?.slug?.current, onChange, value]); return ( <div style={{ padding: "0.75rem", backgroundColor: "#f3f3f3", borderRadius: "4px" }}> {value || ""} </div> ); }, }, }, ], };
关键实现说明
- 动态初始值:通过
initialValue函数读取文档中的slug值,自动拼接成指定格式的path。创建文档时,若slug已生成(比如从title自动转换),path会立即填充对应值。 - 实时同步更新:自定义input组件使用React的
useEffect监听slug字段的变化,一旦slug更新,自动触发path字段的更新,确保两者始终保持一致。同时添加了值对比,避免不必要的重复更新。 - 只读展示优化:自定义了只读的输入框样式,让path字段的展示更直观,符合只读字段的交互预期。
内容的提问来源于stack exchange,提问作者James Hubert
相关产品推荐
相关产品推荐

