react中图片路径为变量的处理

网上搜了很多方法,最简单的就是先定义一个变量A,然后require路径(变量B),赋值给刚才定义的变量A,然后图片路径就是这个变量A

事实上,我面临的情况更复杂些:但原理类似

X页面跳转并传参给Y页面,Y页面接收到参数,然后根据这个参数请求本地json数据,然后获取到图片路径

一步一步来吧

首先是跳转和传参:可以参考这位大佬的

路由文件如下:

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import App from "./component/App";
import Hero from "./component/hero/hero";
export default class BasicRoute extends React.Component {
  render() {
    return (
      <Router>
        <Route exact path="/" component={App} />
        <Route exact path="/hero/:id" component={Hero} />
      </Router>
    );
  }
}

 然后X页面跳转

// router
import { Link } from "react-router-dom";

 

<Link to={`/hero/${item.heroId}`} className="toArchives">
   <span>档案</span>
</Link>

Y页面接收到参数并请求数据,都放在生命周期函数componentDidMount中了

然后先获取参数,使用props.match.params方法

然后用fetch获取本地json,用了json()方式把数据转换一下格式

最后获取到

 // cycleLife function
  componentDidMount() {
    // Route parameters received----heroId
    let heroNum = this.props.match.params.id;
    // get hero's profile
    fetch("../hero.json", {
      // use the get method
      method: "GET"
    })
      .then(res => {
        // use fetch json method
        return res.json();
      })
      .then(data => {
        // use the setState method
        this.setState({
          // the current banner background-----------重点看这里-------
          bannerBgImg: require(`../../herosImg/${
            data[heroNum].bannerBgImgSrc
          }.jpg`),
          // the current banner-----------重点看这里-------
          bannerImg: require(`../../herosImg/${
            data[heroNum].bannerImgSrc
          }.jpg`)
        });
        //
      })
      // If there is an error
      .catch(error => {
        // output the error message
        console.log(error);
      });
  }

require可以像上面这么写

然后render的时候

        <div
          className="bannerAndIconBg"
          // banner-background-------背景图---------
          style={{
            backgroundImage: "url(" + this.state.bannerBgImg + ")"
          }}
        >
          {/* banner */}
          <div className="banner">
            {/* banner-image---图片------- */}
            <img src={this.state.bannerImg} alt="SPIDER-MAN" />
          </div>
        </div>

可以在github上面看我的源码

https://github.com/pk-cat/react

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值