首页 > 解决方案 > 在 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'

标签: reactjsattributesstatejsx

解决方案


您的代码中似乎有错字。初始化一个类字段(就像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>


推荐阅读