草案Js - 添加反应组件

时间:2018-01-29 21:29:26

标签: javascript reactjs draftjs

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

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

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

我见过很多东西,API文档,奇怪的功能,地图等...但我仍然不知道该怎么做。

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

谢谢,

吕西安

1 个答案:

答案 0 :(得分:0)

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

React解决了构建网络"事物的问题。与Composition (as opposed to Inheritance)互动的。创建一个有状态的("基于类的")组件,存储"所有改变的东西"在该组件state内部,当组件内部组件发生更改时,您将不会丢失任何数据。将数据作为道具传递给子组件。

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>
    )
  }
}
相关问题