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)。
我无法在文档中找到componentWillEnter https://facebook.github.io/react/docs/react-component.html ...你在哪里得到它? – Melounek
@Melounek https://medium.com/appifycanada/animations-with-reacttransitiongroup-4972ad7da286 –
正确...我模拟它,并为我“正确地进入”和“离开”。你确定你提供了所有的代码吗?例如,如果您使用connect(),可能会出现此问题:https://stackoverflow.com/questions/37092116/reacttransitiongroup-doesnt-works-with-react-redux-connected-component – Melounek