网上搜了很多方法,最简单的就是先定义一个变量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