hubgit / react-prosemirror

A React component for ProseMirror
https://ow1qi.csb.app/
MIT License
248 stars 51 forks source link

export react context to use class component #43

Open dmc31a42 opened 2 years ago

dmc31a42 commented 2 years ago

Export react context to use class component like Class.contextType or Context.Consumer

Class.contextType

https://ko.reactjs.org/docs/context.html#contextconsumer

class MyClass extends React.Component {
  static editorView = EditorViewContext;
  onClick = () => {
      const view = this.context;
      if (!view) return;
      ...
      const tr = view.state.tr.replaceWith(selection.from, selection.to, node);
      view.dispatch(tr);
  }

  render() {
    ...
  }
}

Context.Consumer

https://ko.reactjs.org/docs/context.html#contextconsumer

class MyClass extends React.Component {
  onClick = (state: EditorState<typeof schema> | null, dispatch?: ((tr: Transaction) => void) | undefined, view?: EditorView<typeof schema> | null) => {
    if (!view) return;
   ...
    const tr = view?.state.tr.replaceWith(selection.from, selection.to, node);
    view.dispatch(tr);
  }

  render() {
    return (
    <EditorProvider
        schema={schema}
        plugins={plugins}
        doc={this.props.initialDoc}
      >
        <Editor />
        <EditorStateContext.Consumer>
          {(state) => 
           <EditorViewContext.Consumer>
             {(view) => (
               <button onClick={() => this.onClick(state, view?.dispatch, view)}>Button</button>
             )}
           </EditorViewContext.Consumer>
          }
        </EditorStateContext.Consumer>
      </EditorProvider>
    )
  }