如何在React.js中以异步方式加载图像悬停效果?

时间:2017-12-13 05:45:25

标签: javascript ajax reactjs

您可能已经看到过这种效果。示例 - https://codepen.io/anon/pen/GEmOQy

但我需要在React中实现相同的方法。我知道我可以使用componentDidMount方法进行ajax,但事情是如何在悬停时显示响应。

我没有使用反应实现悬停的练习,就像我使用:hover的纯css方法一样。

所以欢迎任何解决方案。

2 个答案:

答案 0 :(得分:1)

这是一个非常平坦的问题,并且有很多可能性。我能给出的只是如何做到的基本框架 定义ImageCard组件,其componentDidMount进行API调用。然后在您的父组件(按钮所属的组件)上,存储一个state键,用于管理是否显示该卡:

class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      showCard: false
    };
  }
  render () {
    return (
      <div>
        {
          this.state.showCard &&
        <ImageCard/>
        }
        <button
          onMouseEnter={() => this.setState({ showCard: true })}
          onMouseLeave={() => this.setState({ showCard: false })}
          >Hover Me!</button>
      </div>
    )
  }
}

答案 1 :(得分:0)

在按钮上使用onMouseEnter事件并在其触发时加载新图像,

class SomeComp extends Component{
   coonstructor(){
      this.state = {
          url: 'http://some-intial-url.com'
      }
      this.onMouseEnter = this.onMouseEnter.bind(this)
   }
   onMouseEnter(){
       this.setState({
          url: GetOtherImageURl()
       })
   }
   render(){
      <img src = {this.state.url} />
   }
}