【问题标题】:Draft Js - Add a react componentDraft Js - 添加一个反应组件
【发布时间】:2018-01-29 21:29:26
【问题描述】:

我正在绝望地尝试理解 Draft Js 逻辑,但我没有找到关于该主题的好的教程或文档。

我现在想要的只是一个函数(由下面的按钮触发),它可以在编辑器的末尾添加我的一个反应组件。

然后我希望能够编辑里面的内容,为什么不改变组件类型而不丢失原始文本。

我看过很多很多东西,API 文档、奇怪的函数、地图等等……但我仍然不知道该怎么做。

PS:我的代码目前只是草稿基本编辑器。

谢谢,

吕西安

【问题讨论】:

  • 您要添加什么样的组件?是否使用了来自编辑器的信息?
  • 基本上任何数据显示组件,目前我只想用一个返回

    Hello World!

    的简单组件来成功。

标签: javascript reactjs draftjs


【解决方案1】:

简答:使用包含编辑器、按钮和添加的组件的容器组件。

React 解决了构建与Composition (as opposed to Inheritance) 交互的“事物”网络的问题。创建一个有状态(“基于类”)组件,将“所有更改的内容”存储在该组件的 state 中,然后当组件内部该组件更改时,您不会丢失任何数据。将数据作为 props 传递给子组件。

DraftJS 文档告诉你如何store editor data in state

它看起来像这样:

class Container extends React.Component {
  constructor(props) {
    this.state = {
      editorState: EditorState.createEmpty(),
      // Make sure 'MyComponent` is a React component defined in this file or imported from somewhere
      addedComponentType: MyComponent,
      showAddedComponent: false,
    }
  }

  handleEditorChange = (editorState) => this.setState({editorState})
  // shorthand for `this.setState({editorState: editorState})`

  toggleShowAddedComponent = () => this.setState({
    showAddedComponent: !this.state.showAddedComponent
  })

  render() {
    const {addedComponentType: AddedComponent} = this.state
    // Shorthand for `const AddedComponent = this.state.addedComponentType`
    return (
      <Editor editorState={this.state.editorState} onChange={this.handleEditorChange} />
      {this.state.showAddedComponent && <AddedComponent>Hello World!</AddedComponent>}
      <button onClick={this.toggleShowAddedComponent}>
        {this.state.showAddedComponent ? 'Hide' : 'Show'} Added Component
      </button>
    )
  }
}

【讨论】:

  • 感谢您的宝贵时间,但这并不是我想要做的,我想在编辑器中添加组件,您的示例与编辑器无关。我可能需要的一个用例是用户想要在他的编辑器中添加照片滑块,我想向他提供一个名为 Slider 的反应组件,您可以使用按钮将其添加到草稿中。因此,您可以在任何地方添加任意数量的滑块。
  • 那么,例如,如果编辑器是针对博客文章的,如果用户在编辑器中添加了Slider,那么它会在发布时显示在博客文章中吗?
  • 是的,完全正确。我将使用只读模式的编辑器以同样的方式显示帖子。
  • 看起来这不是你可以单独使用 DraftJS 解决的问题。您将需要某种额外的数据模型来对帖子中元素的位置、类型和内容进行编码。编辑器用于显示富文本。你不能仅仅通过将 JSX 的 text 嵌入到事物中来让它显示一个 react 组件。
  • 首先,在用户提交的文本中(本质上)有evaled javascript 将是一个相当大的安全漏洞。即使只是为了确保安全,您也必须进行广泛的解析/验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 2019-11-11
  • 1970-01-01
相关资源
最近更新 更多