如何为样式分配道具值

How to assign props values to styles

我正在使用 create react app,我需要将 props 值分配给组件的样式。在这种情况下,背景图像 'url' 需要作为道具传递给样式。

index.js

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

import Background from "./background";

import "./styles.css";

function App() {
  return (
    <div className="App">
      <Background source="./assets/image.jpg" />
    </div>
  );
}

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

background.js

import React from "react";

const styles = {
  backgroundImage: "url()"
};

export default class Background extends React.Component {
  render() {
    return <div style={styles.background} />;
  }
}

在下方找到代码 link: codcodesandbox example

您可以像这样创建样式对象并用它更新组件样式道具:


  render() {
    const style = {
      backgroundImage:`url(${this.props.image})`
    }
    return <div style={style} />;
  }

check this code update