【问题标题】:Why new background is not being rendered in styled-components?为什么没有在样式组件中呈现新背景?
【发布时间】: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 才能在样式中工作。

我的控制台输出:

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    您将背景作为src 属性传递给ImageDiv,但使用props.background。试试:

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

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2021-05-20
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 2020-10-25
      • 2015-02-20
      相关资源
      最近更新 更多