javascript - 更改悬停时的图像 React 重新渲染所有子项

标签 javascript reactjs

我需要更改悬停时 img 的 url。 但该函数会触发所有正在渲染的子项。 我找不到一种方法来使该函数单独触发每个 child 。 我尝试创建一些新状态来处理索引,但它不起作用......

const Team = React.createClass ({

    getInitialState : function() {
      return { hovered: false }
    },

    componentDidMount(){
        this.props.fetchTeam();
        document.title = "Equipe | [ Adesign";
    },

    onMouseOver : function () {
      this.setState({ hovered:true });
    },

    onMouseOut : function () {
      this.setState({ hovered:false });
    },

    render(){
        return (
            <div className="wrapper">
                <div className="Team">
                    <HeaderAbout />
                    <h1>EQUIPE</h1>
                    <div className="content-team">
                    {this.props.posts.team.map((singleTeam, i) => {
                        var imgUrl = singleTeam.acf.photo.url;
                        if (this.state.hovered) {
                            imgUrl = singleTeam.acf.gif.url;
                        } else {
                            imgUrl = singleTeam.acf.photo.url;
                        }
                        return(
                            <div key={i} className="single-team col-xs-12 col-sm-6 col-md-4" onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut}>
                                <img className="img-responsive" src={imgUrl}/>
                                <p>{singleTeam.title.rendered}</p>
                            </div>
                        )
                    })}
                    </div>
                </div>
            </div>
        )
    }
});

最佳答案

您想要查看shouldComponentUpdate method :

Invoked before rendering when new props or state are being received. This method is not called for the initial render or when forceUpdate is used.

Use this as an opportunity to return false when you're certain that the transition to the new props and state will not require a component update.

关于javascript - 更改悬停时的图像 React 重新渲染所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39046628/

相关文章:

javascript - 什么是 javascript const 类?

reactjs - 如何在对其中的 ListItem 之一执行操作后更新 ReferenceManyField

javascript - 使用下划线创建 `option`

javascript - 单元测试 react Helm 代码

javascript - Bootstrap : collapse-group within collapse-group

javascript - XState:在没有中间状态的情况下链接多个 promise

javascript - 提供者组件不会重新渲染

reactjs - 我们如何在使用 react 最终形式时在组件中设置状态

javascript - GWT jsinterop java 导出不起作用

javascript - 在当前浏览器中对 ES2015 新数据类型(例如 Set)进行子分类