我想在加载最终的化身图像时加载另一个图像(假化身).其目的是检测props 图像何时加载并更改状态.可能吗?一些 idea ?非常感谢.

class ImageUser extends React.Component {

constructor(props) {
    super(props);
    this.state = {userImageLoaded: false};
    let imageSrc = "";

    if (!this.props.userImage) {
        imageSrc = this.props.noUserImage;
    } else {
        imageSrc = this.props.userImage;
    }

    this.loadingImage = <img className={styles.imageUser}
                     src={this.props.loadingImage} alt="2"/>;

    this.userImage =
        <img onLoad={this.setState({userImageLoaded: true})}
             className={styles.imageUser} src={imageSrc}
             alt="1"/>;

}

render() {
    let image = "";
    if (this.state.userImageLoaded) {
        image = this.userImage;
    } else {
        image = this.loadingImage;
    }
    return (
        <div>
            {image}
        </div>
    );
}
}

export default ImageUser;

推荐答案

有几种方法可以做到这一点,但最简单的方法是显示隐藏的最终图像,然后在加载后将其翻转为可见.

JSBin Demo

class Foo extends React.Component {
  constructor(){
    super();
    this.state = {loaded: false};
  }

  render(){
    return (
      <div>
        {this.state.loaded ? null :
          <div
            style={{
              background: 'red',
              height: '400px',
              width: '400px',
            }}
          />
        }
        <img
          style={this.state.loaded ? {} : {display: 'none'}}
          src={this.props.src}
          onLoad={() => this.setState({loaded: true})}
        />
      </div>
    );
  }
}

Reactjs相关问答推荐

在一个地方调用函数会影响其他地方调用该函数

条件索引路由

CreateBrowserRouter将props 传递给父组件以验证权限

我想删除NextJs中的X轴标签APEXCHARTS

使用REACT-RUTER-V6和ZUSTANDreact 中的身份验证

基本react 应用程序正在触发两次Use Effect

获取未捕获的错误:Gatsby生产版本上的最小化react 错误#418

Redux工具包-useSelector如何通过Reducer引用InitialState?

如何将 MUI X 数据网格单元格方向更改为行级而不是列级?

如何在PrimeReact的表格中修改筛选图标功能

使用reactrouterdom时显示"对象无效作为React子组件"错误

下一个js如何从另一个组件更新组件?

将 ref 转发到所有页面(路由组件)只是为了将其应用于
并具有跳过导航链接(按钮).有没有更好的办法?

React JS:如何判断用户使用的是浏览器 url 还是桌面 electron

Cypress - 在继续之前等待下一个按钮重新出现

MUI 卡组件上的文本未正确对齐

NextJs - 如何从站点 map 生成器中删除重复的 URL?

为什么 React 会多次调用我的应用程序的某些函数?

将 set statehook 函数传递给子路由组件.解构错误

单击按钮时获取react 表中每一行的属性