簡體   English   中英

如何通過Axios.get()中的URL渲染圖像

[英]How to render an Image by URL from Axios.get()

我有問題,需要在React中渲染圖像的幫助。 問題在於該圖像存儲在本地,並且使用Axios.get()與其他一些數據從數據庫中檢索到該圖像的URL。 所有數據顯示正常,但無法渲染該圖像。

 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()上,因為開始時我得到的是未定義的值,但是后來我只是從父頁面提供了相同的路徑(只是要檢查),問題是相同的。

我做錯了...

是否可以提供變量作為圖像源?

如果圖像本身捆綁在您的react應用程序中,那么它將無法正常工作。

require()僅接受靜態

你可以做的事

1.有條件地渲染

const images = {
   image1: require('./image1.jpg'),
   image2: require('./image2.jpg'),
};

然后在您的應用中

    <img src={this.state.lesson.img === 'something_unique' ? images.image1 : images.image2}         //<-----here
        alt="none"
        style={{
        verticalAlign: "middle",
        display: "block",
        margin: "auto",
        marginLeft: "auto",
        marginRight: "auto"
        }}
    />

2.或者,如果您使用捆綁器,則可以獲取公共URL並將其附加。

<img src={process.env.PUBLIC_URL + this.state.lesson.img} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM