我有一个快速问题,我已经被困了一段时间了。我有一些普通的 JS 代码,用于上传文件并显示用户在浏览器中上传的内容。
在我的代码下面,我尝试将普通 JS 转换为 React.js 代码。在 vanilla 中,我可以将 readAndPreview()
嵌套在 previewImages()
中,但在 React.js 中,我收到错误 Unresolved method or function readAndPreview()
在我的 IDE(不是控制台)中,为什么会这样?
我做错了什么以及如何解决它?我愿意接受任何形式的批评:)。
import React, {Component} from 'react';
class Wall extends Component {
constructor(props) {
super(props);
this.previewImages = this.previewImages.bind(this);
this.readAndPreview = this.readAndPreview.bind(this);
}
previewImages() {
const preview = React.createElement('div');
if (this.files) {
[].forEach().call(this.files, this.readAndPreview());
}
readAndPreview() {
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
}
let reader = new FileReader();
reader.addEventListener("load", () => {
let image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
let date = Date.now();
let d = new Date(parseInt(date, 10));
let ds = d.toString('MM/dd/yy HH:mm:ss');
console.log(ds);
let initialCountOfLikes = 0;
const zeroLikes = React.createElement('h1');
let zeroLikesTextNode = zeroLikes.createTextNode(initialCountOfLikes + " likes");
zeroLikes.appendChild(zeroLikesTextNode);
preview.appendChild(image); // makes image appear
preview.appendChild(zeroLikes); // makes like count appear
image.ondblclick = function (event) {
if (initialCountOfLikes === 0) {
console.log("Inside if block");
initialCountOfLikes++;
console.log("initialCountOfLikes++ => " + initialCountOfLikes);
} else if (initialCountOfLikes === 1) {
console.log("inside second else if block");
initialCountOfLikes--;
console.log("initialCountOfLikes-- => " + initialCountOfLikes);
}
zeroLikesTextNode.nodeValue = initialCountOfLikes + " likes";
};
});
reader.readAsDataURL(file);
document.querySelector('#file-input').addEventListener("change", this.previewImages);
}
}
render() {
return (
<div id="file-input-wrapper">
<input type="file"/>
<label htmlFor="file-input" id={"LblBrowse"}></label>
{this.readAndPreview()}
</div>
);
}
}
export default Wall;
最佳答案
如果您想将本地函数嵌套在另一个函数中,欢迎您这样做,但是您需要在其前面加上 function
前缀,如 function readAndPreview() {
。请注意,这只是 previewImages
包含函数内的局部变量,它不是 Wall
上的方法。它无法从 previewImages
外部访问,甚至在 PreviewImages 内部也可以使用 readAndPreview
引用它,而不是 this.readAndPreview
关于javascript - 将 JS 代码转换为 React.js,看不出我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300660/