如何监听react-draft-wysiwyg编辑器中字体族的变更?
监听react-draft-wysiwyg字体族变更的两种方法
方法一:通过Editor的onChange事件追踪字体变化
react-draft-wysiwyg的Editor组件本身提供onChange回调,每次内容(包括字体样式)变更时都会触发。你可以在这个回调里,对比变更前后的选区字体样式,判断字体是否发生变化:
- 在组件state中保存上一次的字体状态
- 在Editor的
onChange里,获取当前选区的行内样式并提取字体族,和上次状态对比:
import { EditorState, getSelection, getCurrentInlineStyle } from 'draft-js'; // 组件内部状态 state = { editorState: EditorState.createEmpty(), lastFontFamily: '' }; handleEditorChange = (editorState) => { const currentInlineStyle = getCurrentInlineStyle(editorState); const currentFontFamily = currentInlineStyle.get('fontFamily') || '默认字体'; // 字体变更时执行自定义逻辑 if (currentFontFamily !== this.state.lastFontFamily) { // 这里写你需要的操作,比如更新状态、发送请求等 console.log('字体已切换为:', currentFontFamily); this.setState({ lastFontFamily: currentFontFamily }); } this.setState({ editorState }); }; // 渲染Editor <Editor editorState={this.state.editorState} onEditorStateChange={this.handleEditorChange} toolbar={{ options: ['fontFamily'], fontFamily: { options: this.state.fonts.map((f) => f.name) } }} />
方法二:自定义fontFamily的下拉组件
直接替换toolbar中fontFamily的默认组件,自己实现下拉选择逻辑,这样就能在选择字体时直接触发自定义回调:
// 自定义字体下拉组件 const CustomFontDropdown = ({ options, onChange }) => { const handleSelect = (e) => { const selectedFont = e.target.value; // 先执行你的自定义逻辑 console.log('选中字体:', selectedFont); // 再调用组件原有onChange,完成Editor的字体样式设置 onChange(selectedFont); }; return ( <select onChange={handleSelect}> {options.map(font => ( <option key={font} value={font}>{font}</option> ))} </select> ); }; // 组件内渲染Editor <Editor editorState={this.state.editorState} onEditorStateChange={(editorState) => this.setState({ editorState })} toolbar={{ options: ['fontFamily'], fontFamily: { options: this.state.fonts.map((f) => f.name), // 替换为自定义组件 component: (props) => <CustomFontDropdown {...props} /> } }} />
第一种方法适合不需要修改下拉组件样式的场景,第二种则能完全自定义下拉框的UI和交互逻辑,按需选择即可。
内容的提问来源于stack exchange,提问作者Jeandré
相关产品推荐
相关产品推荐

