2017-07-07 128 views
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 
    ) 
    } 
} 
+0

您可以使用設置的超時功能。如果有人不打我,我可以發表一個答案。 –

+0

因爲我看不到你的依賴關係,我只是假設你正在使用v4的react-router的最新版本。在文檔中可以找到[動畫轉換](https://reacttraining.com/react-router/web/example/animated-transitions)。 – Ozan

回答

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將延遲渲染到屏幕。

注意我使用的箭頭語法,它將此關鍵字綁定到類上,所以您不必擔心無處不在寫入綁定。