0

我正在尝试制作自己的个人网站,并尝试使用 React 来实现。在这个过程中,我打算让每个部分成为不同的 React 组件。我的计划是让顶部的导航栏能够选择当前“活动”的组件,并实际呈现和显示。另外,当切换到新部分时,我希望旧组件有一个“离开”动画,而新组件有一个“进入”动画(这些都是通过 react-motion 完成的)。但是,目前进入和离开都是同时完成的,因为我同时更改了两个组件的活动状态。有什么方法可以延迟一个组件在另一个组件变为非活动状态后变为活动状态?

容纳每个部分的父组件如下所示:

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
    )
  }
}
4

1 回答 1

0

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

为了让事情更容易理解,我使用放置在 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。之后的 setTimeout 确保组件 2 将延迟渲染到屏幕上。

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

于 2017-07-08T00:30:46.273 回答