为什么新背景没有在样式组件中呈现?
Why new background is not being rendered in styled-components?
我想从 API 中检索图像 url 并将其用作背景,为此我需要使用样式组件。
这是我的应用程序代码:
const API_KEY = `some key`;
class App extends React.Component{
constructor() {
super();
this.state = {
background: ""
}
}
componentDidMount() {
const todayDate = new Date();
this.getImage(todayDate);
}
getImage = async (date) => {
console.log('connecting...');
const URL = `https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`;
const apiCall = await fetch(URL);
const data = await apiCall.json();
this.setState({
background: data.url
});
console.log(data);
}
render(){
return(
<MainContainer>
<Header>Picture</Header>
<Image background={this.state.background}/>
</MainContainer>
)
}
}
来自 Image
的代码:
const ImageDiv = styled.img`
height: 100px;
width: 100px;
margin-top: 15px;
background: url(${props => props.background});
`;
class Image extends React.Component{
render(){
console.log("+++"+this.props.background)
const url = this.props.background;
return(
<ImageDiv src={url}></ImageDiv>
)
}
}
export default Image;
我尝试使用 this.props.background
,但效果不佳。我总是用 background: url();
获取我的元素。我哪里做错了?我想作为道具发送我从 API 获得的新背景 url 并将其设置为样式组件 background
。为了比较,我将背景设置为元素上的图像 src 并且它有效,但我需要 url 才能在样式中工作。
我的控制台输出:
您将背景作为 src
道具传递给 ImageDiv
,但使用 props.background
。尝试:
const ImageDiv = styled.div`
height: 100px;
width: 100px;
margin-top: 15px;
background: url(${props => props.src});
`;
我想从 API 中检索图像 url 并将其用作背景,为此我需要使用样式组件。 这是我的应用程序代码:
const API_KEY = `some key`;
class App extends React.Component{
constructor() {
super();
this.state = {
background: ""
}
}
componentDidMount() {
const todayDate = new Date();
this.getImage(todayDate);
}
getImage = async (date) => {
console.log('connecting...');
const URL = `https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`;
const apiCall = await fetch(URL);
const data = await apiCall.json();
this.setState({
background: data.url
});
console.log(data);
}
render(){
return(
<MainContainer>
<Header>Picture</Header>
<Image background={this.state.background}/>
</MainContainer>
)
}
}
来自 Image
的代码:
const ImageDiv = styled.img`
height: 100px;
width: 100px;
margin-top: 15px;
background: url(${props => props.background});
`;
class Image extends React.Component{
render(){
console.log("+++"+this.props.background)
const url = this.props.background;
return(
<ImageDiv src={url}></ImageDiv>
)
}
}
export default Image;
我尝试使用 this.props.background
,但效果不佳。我总是用 background: url();
获取我的元素。我哪里做错了?我想作为道具发送我从 API 获得的新背景 url 并将其设置为样式组件 background
。为了比较,我将背景设置为元素上的图像 src 并且它有效,但我需要 url 才能在样式中工作。
我的控制台输出:
您将背景作为 src
道具传递给 ImageDiv
,但使用 props.background
。尝试:
const ImageDiv = styled.div`
height: 100px;
width: 100px;
margin-top: 15px;
background: url(${props => props.src});
`;