2017-07-25 59 views
1

我正在用React Transition Group构建一个补充工具栏组件。相关的代码如下:React TransitionGroup不会卸载状态变化的子项目

function FirstChild(props) { 
    const childrenArray = React.Children.toArray(props.children); 
    return childrenArray[0] || null; 
} 

class Sidebar extends Component { 
    componentWillEnter(cb) { console.log('entering'); cb() } 
    componentWillLeave(cb) { console.log('leaving'); cb() } 

    render() { 
    // return sidebar jsx 
    } 
} 

class Nav extends Component { 
    ... 

    toggleSidebar() { 
    const newState = !this.state.show; 
    this.setState({ show: newState }) 
    } 

    render() { 
    return (
     <TransitionGroup component={FirstChild}> 
     { (this.state.show == true) ? <Sidebar /> : null } 
     </TransitionGroup> 
    ) 
    } 
} 

问题是,当我尝试切换边栏时,没有任何生命周期钩子被触发。在第一次点击时,边栏被添加到DOM,componentDidMount被调用,但不是componentWillEnter。当我再次单击以隐藏它时,state.show会正确设置为false,但侧边栏不会隐藏,并且此时不触发生命周期挂钩。

我在想如果我正确地做了三元运算符来有条件地渲染侧边栏,或者是因为我只在TransitionGroup下渲染一个孩子(为此,我使用了FirstChild method found here)。

+0

我无法在文档中找到componentWillEnter https://facebook.github.io/react/docs/react-component.html ...你在哪里得到它? – Melounek

+0

@Melounek https://medium.com/appifycanada/animations-with-reacttransitiongroup-4972ad7da286 –

+0

正确...我模拟它,并为我“正确地进入”和“离开”。你确定你提供了所有的代码吗?例如,如果您使用connect(),可能会出现此问题:https://stackoverflow.com/questions/37092116/reacttransitiongroup-doesnt-works-with-react-redux-connected-component – Melounek

回答

0

该问题出现在渲染逻辑中。出于某种原因,

{ (this.state.show == true) ? <Sidebar /> : null } 

就不会触发TransitionGroup生命周期功能,如ComponentWillEnter/ComponentWillLeave但将其更改为

{ this.state.show && <Sidebar } 

固定的。

相关问题