我正在使用react,现在我想在div中添加一个背景图像。图像url来自props。但是后台没有显示内联css的代码在后面
import React from 'react'
export default function City(props) {
const image = props.img ;
return (
<div className='col-lg-4 col-md-4 col-sm-10 ' style={{
backgroundImage: `url(${image})`}}>
<p>{image}</p>
</div>
)
}
现在我该如何在div中显示背景图像?
您几乎是对的,只需添加div的height
和width
即可。
function City(props) {
const image = props.img;
return (
<div
style={{ height:"300px", width:"300px", backgroundImage: `url(${image})` }}
>
<p>{image}</p>
</div>
);
}
ReactDOM.render(
<City img="https://lh3.googleusercontent.com/ogw/ADea4I6PTtu7DPMQ_R27dQUjfvh2Zol_ehq8vIxq8c3DOw=s32-c-mo" />,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
在styled components
和material ui
库中,您可以将props传递给这样的样式:
样式化组件版本:
https://styled-components.com/docs/basics#adapting-基于道具
物料UI版本:
https://mui.com/styles/basics/#adapting-基于道具
所以最后你可以把你的道具作为道具进一步传递给风格。