【发布时间】:2019-09-06 01:56:17
【问题描述】:
在 React 中渲染图像时我遇到了问题,需要帮助。问题是该图像存储在本地,并且该图像的 URL 是使用 Axios.get() 以及其他一些数据从数据库中检索的。所有数据都显示正常,但无法呈现该图像。
class Lesson extends Component {
state = {
lesson: null
};
componentDidMount() {
Axios.get("https://localhost:44372/api/Lesson/lesson/" +
this.props.location.pathname.substring(
this.props.location.pathname.lastIndexOf("/") + 1)
).then(response => {
console.log("API Response", response);
const newLesson = response.data;
this.setState({
lesson: newLesson,
});
});
}
render() {
return (<div>
<h2 style={{ textAlign: "center" }}>{this.state.lesson.title}</h2>
<p>{this.state.lesson.text}</p>
<p>{this.state.lesson.field1}</p>
<img src={this.state.lesson.img} //<-----here
alt="none"
style={{
verticalAlign: "middle",
display: "block",
margin: "auto",
marginLeft: "auto",
marginRight: "auto"
}}
/>
<div>);
这样,图像就不会显示出来。
我遇到的错误是:不允许加载本地资源:file:///D:/Project/FrontEnd/platform/src/images/python_img.PNG
我可以获得该 img 的唯一方法是手动插入,但这不是我想要的:
<img src={require("D:\\Project\\FrontEnd\\platform\\src\\images\\python_img.PNG")}
我认为问题出在 componentDidMount() 中,因为我在开始时得到一个未定义的值,但后来我只是提供了与父页面相同的路径(只是为了检查),问题是一样的。
我做错了……
是否可以提供变量作为图像源?
【问题讨论】:
标签: javascript html css reactjs jsx