在react中添加变量要求

时间:2018-09-12 14:21:11

标签: javascript reactjs

如何将变量bgImg添加到background-image URL?

let bgImg = props=>props.bgImg;

//this will show error
export const Users = styled.div`
    background-image: url(${require('../../assets/images/' + {bgImg} + '.svg')});
    background-image: url(${require('../../assets/images/' + ${bgImg} + '.svg')});
`;

我已经尝试过了,但是没有用

let x = '../../assets/images/';
let bgImg = props=>props.bgImg;
let result = x + bgImg + ".svg";

结果有误

../../assets/images/function bgImg(props) {
    return props.bgImg;
}.svg

如何获得退货财产?

1 个答案:

答案 0 :(得分:1)

您要寻找的功能是动态导入

import("./math").then(math => {
  console.log(math.add(16, 26));
});

但是您会发现非常有用的是 Loadable 实现:

import Loadable from 'react-loadable';

const LoadableOtherComponent = Loadable({
  loader: () => import('./OtherComponent'),
  loading: () => <div>Loading...</div>,
});

const MyComponent = () => (
  <LoadableOtherComponent/>
);

也许这就是您想要的:

Loadable.Map({
  loader: {
    Bar: () => import('./Bar'),
    i18n: () => fetch('./i18n/bar.json').then(res => res.json()),
  },
  render(loaded, props) {
    let Bar = loaded.Bar.default;
    let i18n = loaded.i18n;
    return <Bar {...props} i18n={i18n}/>;
  },
});