Css 如何通过具有样式化组件的动态名称设置背景图像?

Css 如何通过具有样式化组件的动态名称设置背景图像?,css,reactjs,ecmascript-6,styled-components,Css,Reactjs,Ecmascript 6,Styled Components,我正在尝试用样式化组件设置背景图像。在下面的代码中,我想用不同的div设置背景图像,img_01、img_02、img_03 我看到很多导入img路径并使用它的案例,但我希望根据变量使用动态名称。我需要导入所有图像并设置每个图像吗 import styled, { css } from 'styled-components'; const Div1 = styled.div` width: ${props => props.width}; backgrou

我正在尝试用样式化组件设置背景图像。在下面的代码中,我想用不同的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>
        )
    }
}
import styled,{css}来自“styled components”;
const Div1=styled.div`
宽度:${props=>props.width};
背景:url('asset/images/img_0${props=>props.num}.png');
`;
类主扩展组件{
render(){
返回(
)
}
}

如果不全部导入,我怎么做呢?

您可以这样写:

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


您可以在props中传递完整图像url而不是
num
,然后使用
背景图像:url(${props=>props.someUrl})