我想将下面用香草javascript编写的函数转换为react函数。下面的功能允许用户单击图像输入并将图像附加到包含类“ .editor”的文本区域。
function getImage() {
var file = document.querySelector("input[type=file]").files[0];
var reader = new FileReader();
let dataURI;
reader.addEventListener(
"load",
function() {
dataURI = reader.result;
const img = document.createElement("img");
img.src = dataURI;
document.querySelector(".editor").appendChild(img);
},
false
);
if (file) {
console.log("s");
reader.readAsDataURL(file);
}
}
这是我到目前为止在我的react组件中所做的...我收到以下错误消息
TypeError:editor.push不是函数
Tools.js组件:
function Toolbar() {
const dispatch = useDispatch();
let inputRef = useRef(null);
const editor = 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.push(img);
if(selectedFile) {
console.log("s");
reader.readAsDataURL(selectedFile)
}
};
Editor.js组件:
<>
<div className="center">
<div className="editor" ref={editor} style={editor} contentEditable={true} suppressContentEditableWarning={true}>
<h1>{introText}</h1>
<p>{subText}</p>
</div>
</div>
</>
答案 0 :(得分:0)
不要
editor.push(img);
做
editor.current.push(img);
关于反应文档说
从本质上讲,useRef就像一个“盒子”,可以在其.current属性中保留可变值。
您需要在ref上使用.current属性
在包含Editor.js和Toolbar.js组件的父组件中,ref变量应该在那里,就像这样
import Toolbar from "./toolbar.js"
import Editor from "./editor.js"
const parent = () => {
const editorRef = useRef(null);
/// other code for your component
return (
<div>
<Editor
// other props
editorRef = {editorRef}
/>
<Toolbar
// other props
editor= {editorRef}
/>
</div>
);
}
并在Editor.js文件中执行
Editor.js
const editorComponent = props => {
// some other code
return (
<div ref={props.editorRef}> // will be available because we are passing it
// in the parent component
</div>
);
}
现在在您的
中 Toolbar.js
,您可以通过这种方式访问编辑器道具。
props.editor
这将起作用,因为editor
被存储在同时包含Toolbar
和Editor
组件的组件中。