[英]share value from one component into another in reactjs
为此,我使用了“React Draft Wysiwyg”。 在下面的代码中,我想访问 desktop.js 文件中变量value
editor.js 文件的value
。 我怎样才能做到这一点?
编辑器.js:
export default class TextEditor extends Component {
render(){
return(){
<textarea
disabled
value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
></textarea>
);
}
}
桌面.js:
export const Desktop = () => {
return (
<div className="splitScreen">
<TextEditor/>
</div>
}
首先,您需要将一个函数作为来自桌面组件的 TextEditor 中的道具传递。
像这样<TextEditor onChange={this.onChange}>
。
在桌面组件中声明一个方法如下
onChange = (value) => {
console.log(value);
}
现在像这样在 onEditorStateChange 方法中的 TextEditor 组件中调用此方法
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
this.props.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent()));
};
我建议在 desktop.js 中使用useState
,同时将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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.