如何使用带样式组件的动态名称设置背景图像?

How can I set background image by dynamic names with styled-component?

我正在尝试使用样式化组件设置背景图像。在下面的代码中,我想用不同的 div 设置背景图像,img_01、img_02、img_03、.....

我看到很多案例导入img路径并使用它,但我想根据变量使用动态名称。我需要导入所有图像并设置每个图像吗?

import styled, { css } from 'styled-components';

const Div1 = styled.div`
        width: ${props => props.width};
        background: url('asset/images/img_0${props=>props.num}.png');
    `;

class Main extends Component {
    render() {
        return (
            <div>
                <Div1 width={"475px"} num={1}>

                </Div1>
                <Div1 width={"154px"} num={2}>

                </Div1>

            </div>
        )
    }
}

如何在不全部导入的情况下做到这一点?

你可以这样写:

const Div1 = styled.div`
    width: ${props => props.width};
    background-image: ${props => `url('asset/images/img_0${props.num}.png')`};
`;