代码之家  ›  专栏  ›  技术社区  ›  Alyona

为什么样式化组件中没有呈现新的背景?

  •  0
  • Alyona  · 技术社区  · 7 年前

    我想从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来进行样式设置。

    我的控制台输出: enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   satya164    7 年前

    src 道具 ImageDiv ,但使用 props.background . 尝试:

    const ImageDiv = styled.div`
      height: 100px;
      width: 100px;
      margin-top: 15px;
      background: url(${props => props.src});
    `;