如何动态更改背景图像取决于ReactJs中的路线



我是新来的,从React JS开始。有人能帮我根据路线动态更改背景img吗?所以,准确地说。。。我正在构建配方应用程序,我想根据类别更改背景图像。所以我想用useParams((来做,但它不起作用。

import { useParams } from 'react-router-dom';
function HeaderPicture() {
let params = useParams();
let headerPicture = "";
if(params.name == "/cuisine/Fingerfood") {
headerPicture = "https://images.unsplash.com/photo-1598449426314-8b02525e8733?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1026&q=80"
}
else {
headerPicture = "https://images.unsplash.com/photo-1605851868183-7a4de52117fa?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80"
}
return(
<div className='top-picture' style={{ backgroundImage: `url(${headerPicture})` }}>
<h1>Text1</h1>
<h3>Text2</h3>
</div>
)  
}
export default HeaderPicture

它总是显示第二个图片,所以第一个if((似乎由于某种原因没有正常工作。这是路线,它们运行良好。所有组件都显示出它们的sholud。

<Routes location={location} key={location.pathname}>
<Route path="/" element={<Home />} />
<Route path="/cuisine/:type" element={<Cuisine />} />
<Route path="/searched/:search" element={<Searched />} />
<Route path="/recipe/:name" element={<Recipe />} />
<Route path="/diet/:mediterranian" element={<Mediterranian />} />
</Routes>

提前谢谢。

在尝试操作DOM和useEffect时,应始终使用useState以避免类似的副作用

import {
useParams
} from 'react-router-dom';
import { useEffect, useState } from "react";
function HeaderPicture() {
let params = useParams();
let [headerPicture, setHeaderPicture] = useState("");
useEffect(() => {
if (params.name == "/cuisine/Fingerfood") {
setHeaderPicture("https://images.unsplash.com/photo-1598449426314-8b02525e8733?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1026&q=80")
} else {
setHeaderPicture("https://images.unsplash.com/photo-1605851868183-7a4de52117fa?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80")
}
}, [params.name]);
return ( 
<div className='top-picture'
style = {
{
backgroundImage: `url(${headerPicture})`
}
}>
<h1> Text1 </h1> 
<h3> Text2 </h3> 
</div>
)
}
export default HeaderPicture

为了处理动态路由参数,您需要替换此行:

if(params.name == "/cuisine/Fingerfood") {

这个:

if (params.type === "Fingerfood") {

因为您的参数在路由中被命名为CCD_ 3。

你可以看看这个沙箱,看看这个解决方案的实际工作示例。

最新更新