首页 > 解决方案 > 如何根据文本选择更新下拉列表中的值

问题描述

我正在开发一个基于 React 的 Google Docs 克隆作为一个副项目。我使用 TipTap 作为基础。

我想尝试模仿 Google Docs 中的功能,其中选择字段将根据用户选择的任何文本更新为适当的值(例如,如果用户使用 < 突出显示文本,则“标题 1”将显示在选择字段上h1></h1> 样式)。

这是我想模仿的功能的小视频:https ://i.gyazo.com/18cc57f0285c8c5cd80d5dd6051f0ee7.mp4

这是我迄今为止使用用于选择字段的 React Hook 的代码:

const [font, setFont] = useState('sans-serif')
const handleFontChange = (e) => {
   setFont(e.target.value)
   editor.chain().focus().setFontFamily(e.target.value).run()
}

return (
   <select value={font} onChange={handleFontChange}>
    {fontFamilies.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
   </select>
) 

我试图围绕 React Hooks 和 Selection API,但我被困住了。这在 Javascript/React 中是否可行?

编辑:

我从 Tiptap 的 API 中找到了一个函数,它完全符合我的要求。我想现在的问题是如何将该值更新到选择中?这是我的新代码:

const font = [
     { value: 'sans-serif', label: 'Sans-serif' }, ...
   ]

const [selectedFont, setSelectedFont] = useState([])

const handleFontChange = (obj) => {
    setSelectedFont(obj)
    editor.chain().focus().setFontFamily(obj.value).run()
    console.log(editor.isActive('textStyle', {fontFamily: selectedFont.value})) // prints true if the user clicked on text with the property active, otherwise prints false
}

return (
    <Select
       name="fontFamily"
       options={font}
       isClearable="true"
       isSearchable="true"
       value={selectedFont}
       onChange={(option) => handleFontChange(option)}
    />
)

感觉解决方案非常简单,但我只是想多了。

标签: javascriptreactjstiptap

解决方案


所以我终于想出了该怎么做。我需要传递一个遍历数组的值函数:

const fontList = [
    { label: 'Sans-serif', value: 'sans-serif' },
    ...
]

<Select
    name="fontFamily"
    placeholder="Select font..."
    value={
      editor.isActive('textStyle', {fontFamily: font}) ? (
        selectedFont.find(index => fontList[index])
      ) : ''
    }
    options={fontList}
    onChange={({value: fontSel}) => {
      setFont(fontSel)
      editor.chain().focus().setFontFamily(fontSel).run()
    }}
  />

我只花了整整一周的时间把头发扯掉……很高兴终于完成了。


推荐阅读