首页 > 解决方案 > 在某些事件上禁用反应 css 过渡组

问题描述

我目前有一个仪表板类型的应用程序,它可以从多个松弛通道中提取消息并显示没有任何回复或表情符号的消息。您可以更改要查看的频道。

目前,父状态看起来像这样:

state = {
        selected_channel: window.localStorage.getItem( 'last-slack-ch' ) || 'ABC123'
        selected_date: new Date(),
        channels: {},
        items: [],
        slack_users: {},
        settings: {
            seconds_per_slack_messages_pull: 1
        },
        atBottom: false
    }

在拉入消息之后......或者items,我将该数组传递给一个组件ItemsContainer

这是中的渲染方法ItemsContainer

render() { 

        return (
            <div className="items-container">
                {
                    this.props.items.length > 0 ?
                        <ReactCSSTransitionGroup
                            transitionName='item'
                            transitionEnterTimeout={500}
                            transitionLeaveTimeout={500}>
                        {
                            this.props.items.map( t => { 
                                return (
                                    <Item 
                                        key={ t.usr + '_' + t.ts } 
                                        task={ t } 
                                        user={ this.props.slack_users[ t.usr ] } 
                                        settings={ this.props.settings } 
                                    /> 
                                )
                            } )
                        }
                        </ReactCSSTransitionGroup>
                    :
                        <p className='nothing-found'>No items were found in channel: { this.props.selected_channel }</p>
                }

            </div>
        );
    }

我目前面临的问题是某些事件我不想进行过渡。类似的东西:初始页面加载和切换频道。

我尝试传递一些道具,ItemsContainer这些道具将确定什么 transitionName 到ReactCSSTransitionGroup... 但事情并没有真正运作得很好。

有人有这方面的经验吗?

标签: reactjsreact-transition-group

解决方案


很难从您的代码中确切地知道您将如何实现它,但您可以在组件key的顶层添加一个属性。该属性通常用于识别集合中的子项,但也可以在这些情况之外使用。当一个键发生变化时,React 会创建一个新的组件实例而不是重新渲染现有的(https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation - 完全不受控制的组件,带有密钥)。divItemsContainerkey

所以尝试重写ItemsContainer为:

render () {
  return (
    <div className="items-container" key={this.props.selected_channel}>
      // Transition code that will only apply within the selected channel.
    </div>
  );
}

这应该可以解决切换信道问题。因此,当ItemsContainer接收到新props.selected_channel值时,您应该避免过渡动画。


推荐阅读