【问题标题】:How to structure a render function with img.src如何使用 img.src 构造渲染函数
【发布时间】:2020-01-16 19:11:30
【问题描述】:

我的render() 函数中有以下代码,我试图在状态发生变化时动态地更改图像的高度和宽度:

render() {

    const imageURL = photos[this.state.currentImage].url;

    const base_image = new Image();
    base_image.src = imageURL;

    var wrh = base_image.width / base_image.height;
    var newWidth = 600;
    var newHeight = newWidth / wrh;

    return (

       <img height={newHeight} width={newWidth}>
    )

}

我知道我必须添加一个base_image.onload 函数以确保在设置base_image.src 时图像开始加载但代码跳转到return() 并以错误的height 和width 呈现图像值,因为图像没有完成加载,我没有获取正确的值。如何构建我的代码,以便在 base_image 完成加载之前不会渲染图像?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您可以使用state variable 来存储图像的比例。在render 方法中,您可以使用条件渲染来阻止显示图像,直到已计算出比率

    const width = 600;
    
    class YourComponent {
      constructor(props) {
        super(props);
        this.state = {
          ratio: undefined,
          currentImage: 0
        };
        this.image = new Image();
      }
    
      componentDidMount() {
        this.img.onload = () => {
          this.setState({
            ratio: this.img.naturalWidth / this.img.naturalHeight  
          });
        };
        this.img.src = photos[this.state.currentImage].url;
      }
    
      componentDidUpdate(prevProps, prevState) {
        if (this.state.currentImage !== prevState.currentImage) {
          this.img.src = photos[this.state.currentImage].url;
        }
      }
    
      render() {
        const {ratio} = this.state;
        return ratio && <img width={width} height={width/ratio}>;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      相关资源
      最近更新 更多