首页 > 解决方案 > 我正在尝试在 jsx-react 中动态添加图像,但它不会显示

问题描述

import React from "react";
import ReactDOM from "react-dom";

var bImg = prompt("Which image do you want to set as background image?");
const bStyle = {
  backgroundImage: "url(bImg)" // i stored the link here 
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <div style={bStyle}> // I stored it here but still it won't show up
    <h1>Hello world!!</h1>
  </div>,
  rootElement
);

其余的工作正常,但背景图像不会从我在提示中输入的 URL 加载。该错误显示为“bImg”分配了一个值,但未使用它。

标签: javascriptcssreactjsjsx

解决方案


输出:

在此处输入图像描述

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

var bImg = prompt("Which image do you want to set as background image?");
const bStyle = {
  backgroundImage: `url(${bImg})` // i stored the link here
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <div style={bStyle}>
    // I stored it here but still it won't show up
    <h1>Hello world!!</h1>
  </div>,
  rootElement
);

StackBlitz 演示


推荐阅读