我需要访问“编辑器”,它是在我的父组件(Editor.js)中定义的引用。我的子组件(Toolbar.js)具有需要编辑器参考的功能 imgChangeHandler。做这个的最好方式是什么 ?
Editor.js(父):
import React, {useRef, useState} from "react"
const editor = useRef(null);
function Editor() {
...
return (
<>
<div className="center">
<div
className="editor"
style={editorStyle}
ref={editor}
contentEditable={true}
suppressContentEditableWarning={true}
>
<h1>introText</h1>
<p>subText</p>
</div>
</div>
</>
)
}
export default Editor
Toolbar.js(子):
import React, {useState} from "react"
function Toolbar() {
const dispatch = useDispatch();
const inputRef = useRef(null);
const [selectedFile, setSelectedFile] = useState(null);
const imgChangeHandler = e => {
e.preventDefault();
setSelectedFile(e.target.files[0]);
let reader = new FileReader();
let dataURI = reader.result;
const img = React.createElement("img",{src: dataURI});
editor.current.push(img); // need access to editor ref here
if(selectedFile) {
console.log("s");
reader.readAsDataURL(selectedFile)
}
};
...
}
export default Toolbar