【发布时间】:2020-05-26 14:53:52
【问题描述】:
我想在 React 中显示位于 src/images 文件夹中的图像。此图像有一个 PATH 存储在数据库中,看起来像这样“../images/profilepic.jpg”。我进行 api 调用,获取 PATH 字符串并将其保存在名为 profilepic 的状态中,到目前为止,这一切正常。然后我将状态变量分配给 profilepic 变量,当我“console.log()”它时正确分配。
问题是当我使用<img src{profilepic} alt="myprofilepic"/> 时,我无法在网站上显示此图像。我已经尝试了过去问题中建议的几乎所有方法,但都没有奏效。我试图将状态this.state.profilepic(分配给它的字符串PATH)作为道具传递给单独的组件,但我仍然遇到同样的问题。使用 <img src=(require{profilepic}) 会产生错误,因为 require 只会使用字符串 URL。
任何人都可以指出一个教程的方向,其中图像作为 URL/路径字符串存储在数据库中,并在 React 中调用和使用。即使它不是一个完整的项目,我也想知道如何从 React 前端完成。如果这不是在 React 中处理动态图像的推荐方法,那么将图像作为 BLOB 存储在数据库中,然后在 React 中调用实际图像本身而不是 PATH 是否更可取?
获取调用:
getUserdetails(){
const userid = this.state.userid;
axios.get(`http://localhost:5000/getuser/details?userid=${userid}`)
.then(json => {
if(json.data.success){
this.setState({
username: json.data.username,
email: json.data.email,
fullname: json.data.fullname,
company: json.data.company,
profilepic: json.data.propic
})
profilepic = this.state.profilepic
console.log(profilepic)
this.newprofile(profilepic)
}
})}
渲染输出
return (
<div className="accout-page">
<div className="sidebar">
<Images profpic={profilepic} />
<p><input type="file" onChange={this.onchangeImage} /><button type="button" onClick={this.uploadimage}>Upload</button></p>
<p>Username: {username}</p>
<p>Full Name: {fullname}</p>
<p>Company: {company}</p>
<p>Email: {email}</p>
</div>
<div className="content">
<h1>Edit your details here</h1>
<div className="form-error-info">{updateMessage}</div>
<form>
<div className="form-group">
<label>Full Name:</label>
<input
type="text"
placeholder={fullname}
onChange={this.onNameChange} required/></div>
<div className="form-group">
<label>Company:</label>
<input
type="text"
placeholder={company}
onChange={this.onCompanyChange} required/></div>
<div className="form-group">
<label>Current Password:</label>
<input
type="password"
placeholder="enter current password"
onChange={this.onoPassChange} required/></div>
<div className="form-group">
<label>New Password:</label>
<input
type="password"
placeholder="enter new password"
onChange={this.onPassChange} required/></div>
<button className="btn btn-light" type="button" onClick={this.onSubmit}>Update</button>
</form>
</div>
</div>
)
图像组件:
class Images extends React.Component{
render(){
const profpic = this.props.profpic;
console.log(profpic)
return(
<div>
<img src={profpic} alt="profile pic" width="100px" height="100px" />
</div>
)}}
【问题讨论】:
-
你能从你的代码中添加 sn-ps 吗?那样很难理解。
标签: reactjs