javascript - 如何根据文本选择更新下拉列表中的值
问题描述
我正在开发一个基于 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)}
/>
)
感觉解决方案非常简单,但我只是想多了。
解决方案
所以我终于想出了该怎么做。我需要传递一个遍历数组的值函数:
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()
}}
/>
我只花了整整一周的时间把头发扯掉……很高兴终于完成了。
推荐阅读
- python-3.6 - Sphinx 文档构建在私有 GitHub 存储库的 readthedocs 上失败
- docker - 我在烧瓶 gunicorn 应用程序上遇到了 Nginx 和 docker conf 的问题
- reactjs - 为 webfontloader 定位样式表的路径 - ReactJS
- python - 如何使用具有多个 agruments 的函数运行多处理 python 请求
- javascript - 为什么警报显示此代码中的先前状态?
- c# - CS1061:“字符串”类型不包含“classChoice”的定义,并且没有扩展方法“classChoice”
- javascript - 关于条件语句和定义变量的一个简单问题
- javascript - 使用 .map 整数作为另一个地图的目标
- swift - 从 firebase 下载评级,第一个评级总是显示为 nan
- tensorflow - 在项目中使用 go 模块时如何导入 tensorflow go 包?