reactjs - 在 React JSX 中使用 STATE 作为 html ATTR
问题描述
我在 ReactJS 中工作,并且有一个存储在 State 中的照片的 URL。我想使用该 photoURL 在我的组件渲染中调用图像。但是当我使用正常src={this.state.photoURL}
时它会引发错误。
理想情况下,我可以将它用作容器中的背景图像,如下所示:
<div className='photo-cont' style='background-image:url({this.state.photoURL}); background-size:cover;'
我已经尝试过这个并且作为一个正常的img,在花括号周围有和没有引号,有和没有花括号本身。
class Foo extends Component {
state: {
photoURL: 'www.foobar.com/foo.jpg',
}
render () {
return(
<img src={this.state.photoURL}></img>
)
}
}
我不断收到以下错误:'TypeError:无法读取属性'photoURL' of null'
解决方案
您的代码中似乎有错字。初始化一个类字段(就像state
你应该使用=
.
我添加了photoURL
作为图像和 div 的背景图像的示例。请记住在 div 上设置宽度/高度/填充以显示图像:
class Foo extends React.Component {
state = {
photoURL: 'https://unsplash.it/400/200',
}
render () {
return(
<div>
<img src={this.state.photoURL}/>
<div style={{
width: '400px',
height: '200px',
backgroundImage: `url(${this.state.photoURL})`,
}}/>
</div>
)
}
}
ReactDOM.render(<Foo/>, document.getElementById('root'));
<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>
<div id="root"></div>
推荐阅读
- android - 缓存控制在某些 Android 浏览器中不起作用
- windows - Zookeeper 的 Windows 10 环境变量问题
- c - 在 C 中使用三元运算符时,char * 和 const char * 是否兼容?
- java - 如何使用Spring根据查询参数键和值进行过滤
- docker - 如何在 Cloud Run 上自动部署 Cloud Build 构建的 docker 镜像
- azure - Azure - 无法从私有 Azure 存储库运行映像
- java - 当密钥使用文件夹结构定义时,我们如何从 AWS S3 存储桶中获取对象?
- c++ - 如何停止这个模板化函数值初始化一个新构造的对象?
- visual-studio-2019 - Visual Studio 2019 的指标边距上的各种括号是什么意思?
- arrays - 将 JSON 结构转换为数组:Groovy