[英]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.