【问题标题】:Using STATE as html ATTR in React JSX在 React JSX 中使用 STATE 作为 html ATTR
【发布时间】:2019-11-23 20:25:05
【问题描述】:

我在 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: Cannot read property 'photoURL' of null'

【问题讨论】:

  • state: {...改成state = {...能用吗?

标签: reactjs attributes state jsx


【解决方案1】:
class Foo extends Component {
 contructor(props) {
  super(props)
  this.state = {
   photoURL: 'www.foobar.com/foo.jpg',
  }
 }

  render () {
    return(
      <img src={this.state.photoURL}></img>
    )
  }
}

尝试使用 contructor() 来定义你的状态

【讨论】:

    【解决方案2】:

    您的代码中似乎有错字。要初始化一个类字段(如state,您应该使用=

    我将photoURL 的示例添加为图像和div 的背景图像。记得在 div 上设置 width/height/padding 以显示图像:

    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>

    【讨论】:

      【解决方案3】:
      import logo from './logo.png';
      class Foo extends Component {
        render () {
          return(
            <img src={logo}></img>
          )
        }
      }
      

      查看他们的文档: https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files

      【讨论】:

      • 这假定照片是静态资产。我认为这不是 OP 正在寻找的。他特意问了如何通过state设置src属性
      • 如果不需要,为什么还要使用状态?你就是这样教新人的?
      • 由于 OP 在他的原始代码中使用了状态,我认为可以合理地假设他希望 photoURL 在某些能力上是动态的。
      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 2017-01-11
      • 2018-07-26
      • 2021-03-22
      • 2021-07-10
      相关资源
      最近更新 更多