在 React 组件中动态导入图像

IT技术 reactjs
2021-05-04 22:12:29

我正在尝试在某些 React 组件中动态加载图像。我使用require而不是简单地传递路径以提高性能。

我收集到我可以使用内联require并且它确实有效。但是,当我尝试作为 a 传递时prop,出现错误。

我究竟做错了什么?

编辑:原来这两项工作,我在做其他错误的事情是抛出错误。(奖金问题仍然适用)

import React from 'react';

// This works
export SomeComponent = () => (
  <div>
    <img src={require(`../images/my-logo.svg`)} />
  </div>
)

// This works too!
export SomeComponent = ({image}) => (
  <div>
    <img src={require(`../images/${image}`)} />
  </div>
)

<SomeComponent image="my-logo.svg" />

额外问题:这可以用 ES6import还是 CommonJs来完成require

2个回答

不确定它是否会起作用,但您可以尝试:

class Image extends React.Component {
  constructor(props) {
    super(props)
    this.state = { src: null }
  }

  componentDidMount() {
    this.loadImage(this.props.name)
  }

  componentDidUpdate(prevProps) {
    if(prevProps.name !== this.props.name) {
      this.loadImage(this.props.name)
    }
  }

  loadImage(name) {
    import(`../images/${name}`)
      .then(image => {
        console.log(image); // this may be object with image inside...
        this.setState({ src: image })
      })
  }

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

对于 React 16+,@Tomasz Mularczyk 的回答需要一个小的调整:

loadImage(name) {
    import(`../images/${name}`)
      .then(image => {
        console.log(image); // This will show an object with a `default` property as the image you imported
        this.setState({ src: image.default })
      })
 }

完整来源:

class Image extends React.Component {
  constructor(props) {
    super(props)
    this.state = { src: null }
  }

  componentDidMount() {
    this.loadImage(this.props.name)
  }

  componentDidUpdate(prevProps) {
    if (prevProps.name !== this.props.name) {
      this.loadImage(this.props.name)
    }
  }

  loadImage(name) {
    import(`../images/${name}`)
      .then(image => {
        console.log(image); // This will show an object with a `default` property as the image you imported
        this.setState({ src: image.default })
      })
  }

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