【发布时间】:2019-03-03 07:04:37
【问题描述】:
我想从 API 中检索图像 url 并将其用作背景,为此我需要使用 styled-components。 这是我的应用代码:
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,并将其设置为 styled-components background。为了比较,我将背景设置为元素上的图像 src 并且它可以工作,但我需要 url 才能在样式中工作。
【问题讨论】: