React中使用Trix编辑器传入带样式内容时CSS样式被清除的解决方案求助
解决方案
Trix默认内置了HTML内容过滤机制,会自动剥离不在白名单内的标签和属性,你遇到的样式丢失是因为内联style属性默认不在Trix的解析白名单中,且React动态绑定hidden input值的时机和Trix初始化顺序不匹配,触发了严格过滤逻辑,可按以下步骤解决:
- 第一步:提前配置Trix属性白名单,允许保留style属性
在引入Trix之后、组件初始化前添加全局配置,将style属性加入文本解析白名单:
import Trix from "trix" // 配置允许span标签保留内联style属性 Trix.config.textAttributes.style = { tagName: "span", parse: element => element.getAttribute("style"), compose: value => ({ style: value }) }
如果需要支持其他标签的内联样式,可以对应修改tagName或添加多条配置。
- 第二步:调整内容赋值逻辑,改用Trix官方API加载内容
不要通过给hidden input绑定value的方式传入带样式的内容,改为等待Trix编辑器初始化完成后,调用loadHTML方法加载内容,类组件参考代码如下:
class YourTrixComponent extends React.Component { trixInput = React.createRef() componentDidMount() { const editorEl = this.trixInput.current const inputId = "trix" + this.props.index // 监听Trix初始化完成事件 editorEl.addEventListener("trix-initialize", () => { // 加载带样式的HTML内容 const content = this.props.journals.article.paragraphs[this.props.index].paragraph editorEl.editor.loadHTML(content) // 可选:监听内容变更,同步编辑结果到hidden input editorEl.addEventListener("trix-change", () => { document.getElementById(inputId).value = editorEl.value }) }) } render() { const inputId = "trix" + this.props.index return ( <> <trix-editor style={{ minHeight: 300 }} input={inputId} ref={this.trixInput} /> <input type="hidden" id={inputId} className={classnames('', { 'is-invalid': errors.paragraph })} /> </> ) } }
内容的提问来源于stack exchange,提问作者ertemishakk
相关产品推荐
相关产品推荐

