首页 文章

草案Js - 添加反应组件

提问于
浏览
-1

我正在努力去了解Draft Js逻辑,但是我没有找到关于这个主题的好的教程或文档 .

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

然后我希望能够编辑内部的内容,为什么不在不丢失原始文本的情况下更改组件类型 .

我见过很多东西,API文档,奇怪的函数, Map 等...但我仍然不知道如何做到这一点 .

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

谢谢,

吕西安

1 回答

  • 0

    简答:使用容纳编辑器,按钮和添加组件的容器组件 .

    React解决了构建与Composition (as opposed to Inheritance)交互的"things"网络的问题 . 创建一个有状态("class-based")组件,在该组件的 state 中存储"all the stuff that changes",然后当该组件内的组件发生更改时,您不会丢失任何数据 . 将数据作为道具传递给子组件 .

    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>
        )
      }
    }
    

相关问题