渲染组件延迟?



我正在尝试创建自己的个人网站,并尝试使用 React 来做到这一点。在这个过程中,我打算使每个部分成为不同的 React 组件。我的计划是让顶部的导航栏能够选择当前"活动"的组件,并实际呈现和显示。此外,当切换到新部分时,我希望旧组件具有"离开"动画,而新组件具有"进入"动画(这些是通过反应运动完成的(。但是,目前输入和离开是同时完成的,因为我同时更改了两个组件的活动状态。有没有办法延迟一个组件在另一个组件变为非活动状态后变为活动状态?

包含每个部分的父组件如下所示:

class Website extends React.Component {
constructor(props){
super(props)
this.state = {
homeActive: true,
aboutActive: false
}
homeActivator(){
this.setState({
homeActive: true,
aboutActive: false
})
}
aboutActivator(){
this.setState({
homeActive: false,
aboutActive: true
})
}
render(){
return (
<div>
<NavBar handleHome={this.homeActivator.bind(this)} handleAbout=
{this.aboutActivator.bind(this)}/>
<Home active={this.state.homeActive} />
<About active={this.state.aboutActive} />
</div>
}

然后其中一个"部分"如下所示:

class Home extends React.Component{
render() {
let content = (
<div>
Home
</div>
)
if (!this.props.active){
return (
//Some jsx that results in the content leaving the page
)
}
return(
//Some jsx that results in the content entering the page
)
}
}

我没有很多时间来回答这个问题,但我想出了我能想到的最好的例子。它不是您要做的事情的精确复制品,但非常相似,因此,如果您了解它,您将能够很容易地找出您的问题。

为了使事情更容易理解,我正在使用放置在 React 类中的方法模拟组件。 显然,在现实世界中,您将从其他文件导入组件。我相信你会明白发生了什么。

export default class Example extends Component {
constructor(props) {
super(props)
this.state = {
c1: true,
c2: false
}
}
// Component One
renderc1() {
return (
<div>
I am component one
</div>
)
}
// Component Two
renderc2() {
return (
<div>
I am component two
</div>
)
}
changeComponents = () => {
this.setState({ c1: false })
setTimeout(() => {
this.setState({ c2: true })
}, 1500)
}
render() {
return (
<div className="example">
{this.state.c1 ? this.renderc1() : null}
{this.state.c2 ? this.renderc2() : null}
<button onClick={this.changeComponents}>Click me</button>
</div>
)
}
}

单击该按钮将触发 changeComponents 函数,然后立即将 "c1" 的状态设置为 false。在此之后的设置超时可确保组件 2 将延迟呈现到屏幕。

请注意我使用的箭头语法,它将 this 关键字绑定到类,因此您不必担心在任何地方编写绑定 this。

最新更新