UNPKG

1.49 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import { defaultEditorState } from '@/utils/default';
4
5// 利用Provider来内部维护多组件之间共享的editorState
6export const ArchEditorContext = React.createContext({});
7
8export class ArchEditorProvider extends React.Component {
9 constructor(props) {
10 super(props);
11 this.setEditorState = this._setEditorState.bind(this);
12 this.state = {
13 editorContext: {
14 contextEditorState: defaultEditorState,
15 setContextEditorState: this.setEditorState,
16 },
17 };
18 }
19
20 static getDerivedStateFromProps(props, state) {
21 const { value } = props;
22 if (value) {
23 return {
24 editorContext: {
25 ...state.editorContext,
26 contextEditorState: value,
27 },
28 };
29 }
30 return null;
31 }
32
33 _setEditorState(v) {
34 const { editorContext } = this.state;
35 const { value, onChange } = this.props;
36 if (!value) {
37 this.setState({
38 editorContext: {
39 ...editorContext,
40 contextEditorState: v,
41 },
42 });
43 }
44 if (onChange) onChange(v);
45 }
46
47 render() {
48 const { children } = this.props;
49 const { editorContext } = this.state;
50 return <ArchEditorContext.Provider value={editorContext}>{children}</ArchEditorContext.Provider>;
51 }
52}
53
54ArchEditorProvider.propTypes = {
55 value: PropTypes.any,
56 onChange: PropTypes.func,
57 children: PropTypes.any,
58};