【问题标题】:How to render an Image by URL from Axios.get()如何通过 Axios.get() 中的 URL 渲染图像
【发布时间】: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 的唯一方法是手动插入,但这不是我想要的:

&lt;img src={require("D:\\Project\\FrontEnd\\platform\\src\\images\\python_img.PNG")}

我认为问题出在 componentDidMount() 中,因为我在开始时得到一个未定义的值,但后来我只是提供了与父页面相同的路径(只是为了检查),问题是一样的。

我做错了……

是否可以提供变量作为图像源?

【问题讨论】:

    标签: javascript html css reactjs jsx


    【解决方案1】:

    如果图像本身捆绑在您的 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} />
    

    【讨论】:

    • 按照您的建议,将所有图像移至公用文件夹中,然后使用您的线路进行渲染,一切正常。谢谢你。
    猜你喜欢
    • 2020-03-10
    • 2021-09-13
    • 2015-09-27
    • 2020-10-15
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2022-06-11
    相关资源
    最近更新 更多