我建议useState
在 desktop.js 中使用,同时将状态textValue
和setState
函数作为道具传递给TextEditor
组件:
import React, { useState } from "react";
export const Desktop = () => {
const [textValue, setTextValue] = useState("");
return (
<div className="splitScreen">
<TextEditor textValue={textValue} setTextValue={setTextValue} />
</div>
);
};
然后使用里面的两个道具TextEditor
:
import React, { Component } from "react";
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw } from "draft-js";
import "./editor.css";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from "draftjs-to-html";
export default class TextEditor extends Component {
state = {
editorState: EditorState.createEmpty(),
};
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
};
render() {
const { editorState } = this.state;
// here you set the textValue state for the parent component
this.props.setTextValue(
draftToHtml(convertToRaw(editorState.getCurrentContent()))
);
return (
<div className="editor">
<Editor
editorState={editorState}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={this.onEditorStateChange}
/>
<textarea
disabled
text_value={this.props.textValue} // here you use the textValue state passed as prop from the parent component
></textarea>
</div>
);
}
}