我想动态地改变应用在Body上的背景图片。我使用unsplash api来获取随机照片。应用在Body标签上的css如下:index.css
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-image: url("https://images.unsplash.com/photo-1506501139174-099022df5260?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEzNjgxNH0");
background-repeat: no-repeat;
}
下面是功能组件的代码,更新了状态中的backgroundImage。我想把状态下的动态url应用到Body标签的css中。请看下面的代码。
import React, { useState, useContext } from "react";
import { Row, Col, Input, Button, Divider, Typography } from "antd";
import axios from "axios";
import { GlobalContext } from "../../contexts/GlobalState";
const { Title } = Typography;
export const SearchBox = () => {
const [location, updateLocation] = useState("");
const { updateBackground } = useContext(GlobalContext);
const onCityChange = (e) => {
updateLocation(e.target.value);
};
const onSearch = () => {
axios
.get(
`https://api.unsplash.com/search/photos?query=${location}&client_id=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa`
)
.then((response) => {
const url = `"url('${response.data.results[5].urls.full}')"`;
updateBackground(url);
})
.catch((error) => {
console.log(error);
});
};
return (
<>
<Row>
<Col span={24} style={{ marginTop: 30 }}>
<Title level={4}>Weather App</Title>
</Col>
</Row>
<Row>
<Col
span={24}
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<Input
size="large"
placeholder="City Name"
onChange={(e) => onCityChange(e)}
/>
<Button
size="large"
type="primary"
onClick={onSearch}
style={{ marginLeft: "5px" }}
>
Search
</Button>
</Col>
</Row>
<Divider plain></Divider>
</>
);
};
我如何动态更新Body的背景图片?
谢谢大家
你可以使用styled-components轻松地做到这一点。你可以使用这个。
const GlobalStyle = createGlobalStyle`
body {
background: ${props => (props.something ? url(imageone) : url(imagetwo))};
}
`
这样你就可以传入一个道具,然后根据这个道具来渲染不同的东西。我这样做是为了给我的应用渲染一个不同的背景图片。
文档在这里。https:/styled-components.comdocsapi。
如果你需要更多细节,请告诉我