我需要渲染我上传的所有图像的宽度和高度。 我将图像放到数据库中,并将其呈现为src base64字符串。 我的建议是渲染整个img>获取宽度>将其放在状态上,但是这项工作不是我期望的。 首先,仅在加载img时才获取宽度,然后我需要重新渲染显示宽度的元素。 我认为第二个问题是我需要修改状态以渲染具有其自身属性的所有图像)
import React , {useState, useEffect} from 'react';
import Dexie from "dexie";
const Main = () => {
//set the database
const db = new Dexie("ReactDexie");
//create the database store
db.version(1).stores({
posts: "title, content, file, type"
})
db.open().catch((err) => {
console.log(err.stack || err)
})
//set the state and property
const [postTitle, setTitle] = useState("");
const [postContent, setContent] = useState("");
const [postFile, setFile] = useState("");
const [posts, setPosts] = useState("");
const [type, setType] = useState("");
const [width, setWidth] = useState(0);
//read the file and decode it
const getFile = (e) => {
console.log('set:',e)
setType(e[0].type)
let reader = new FileReader();
reader.readAsDataURL(e[0]);
reader.onload= (e) => {
setFile(reader.result);
}
}
const deletePost = async(id) => {
console.log(id);
db.posts.delete(id);
let allPosts = await db.posts.toArray();
//set the posts
setPosts(allPosts);
}
let post = {
title: postTitle,
content: postContent,
file: postFile,
type: type,
width:width
}
//submit
const getPostInfo = (e) => {
e.preventDefault();
if(postTitle !== "" && postContent !== "" && postFile !== ""){
db.posts.add(post).then(async() => {
//retrieve all posts inside the database
let allPosts = await db.posts.toArray();
//set the posts
setPosts(allPosts);
});
}
}
useEffect(() => {
//get all posts from the database
const getPosts = async() => {
let allPosts = await db.posts.toArray();
setPosts(allPosts);
}
getPosts();
}, [])
let postData;
if(posts.length > 0) {
var image = document.createElement('img');
postData = <div className="postsContainer">
{
posts.map(post => {
return <div className="post" key={post.title}>
<div style={{backgroundImage: "url(" + post.file + ")" }} />
<h2>{post.title}</h2>
<p>{post.content}</p>
<p onClick={() => console.log(post.width)}>Width:{post.width}</p>
<button className="delete" onClick={() => deletePost(post.title)}>Delete</button>
</div>
})
}
</div>
}else{
postData = <div className="message">
<p>There are no posts to show</p>
</div>
}
return (
<React.Fragment>
<form onSubmit={getPostInfo}>
<div className="control">
<label>Title</label>
<input type="text" name="title" onChange={e => setTitle(e.target.value)} />
</div>
<div className="control">
<label>Content</label>
<textarea name="content" onChange={e => setContent(e.target.value)} />
</div>
<div className="control">
<label htmlFor="cover" className="cover">Choose a file</label>
<input type="file" id="cover" name="file" onChange={e => {
getFile(e.target.files)}} />
</div>
<input type="submit" value="Submit" />
</form>
<p>WIDTH:{post.width}</p>
<div>
{postData}
</div>
</React.Fragment>
);
}
export default Main;
如何呈现img宽度?我只有在加载图像时才能获取它。是否有办法从base64字符串获取此图像?