我想从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();
background
. 为了比较,我将background设置为image src on element,它可以工作,但我需要url来进行样式设置。
我的控制台输出: