簡體   English   中英

ReactJS變量更改未呈現元素

[英]ReactJS variable change isn't rendering element

我有一個相當簡單的情況(我將ReactJS與A-Frame / A-Frame React一起使用,但這實際上不會影響到這里)。

我有一個實體,向用戶暗示他們可以單擊/滑動對象。 我希望該實體在用戶單擊該對象后消失,然后在10秒后重新出現。

我是React的新手,因此在這里可能做錯了什么:

  1. 在我的JS文件的頂部(在我的導入之后,但在class開始之前,我正在執行let showHinter = true;

  2. 我的render()方法中有一個實體,如下所示:

     <AFrameEntity events={{ click: (ev) => { showHinter = false; setTimeout(() => { console.log("showHinter Value:", showHinter) /* ↑ This fires, but ↓ this doesn't do anything */ showHinter = true; console.log("showHinter Value:", showHinter) }, 5000) } }} > </AFrameEntity> 
  3. 我的“ hinter”組件與此類似,例如:

     { <AFrameEntity /* Bunch of irrelevant stuff here */ > // fade out { !showHinter && <a-animation attribute="material.opacity" dur="1000" fill="forwards" from="1" to="0" repeat="0"></a-animation> } //fade in { showHinter && <a-animation attribute="material.opacity" dur="1000" fill="forwards" from="0" to="1" repeat="0"></a-animation> } </AFrameEntity> } 

單擊時, showHinter正確設置為false並且該元素消失。 但是,它再也不會出現。 我的控制台日志確實發生了,並且showHinter === false ,但是我的淡入動畫從未發生,並且使用react的devtools檢查元素顯示了我的淡出動畫實體,而不是我的淡入動畫實體(當showHinter === true

所以基本的問題是,為什么React不對我的變量更改做出反應? 我是否需要強迫它以某種方式重新渲染?

您應該通過狀態進行所有更改,以影響視圖或期望重新渲染的位置。

在您的情況下,您可以執行以下操作(未經測試):

<AFrameEntity
events={{
  click: (ev) => {

    this.setState({showHinter: false)};

    setTimeout(() => {
      console.log("showHinter Value:", this.state.showHinter)

      /* ↑ This fires, but ↓ this doesn't do anything */

      this.setState({showHinter: true)};
      console.log("showHinter Value:", this.state.showHinter)
    }, 5000)

  }
}}

並檢查渲染功能中的狀態。

{

  <AFrameEntity /* Bunch of irrelevant stuff here */ >

    // fade out
    {
     !this.state.showHinter && 
      <a-animation 
        attribute="material.opacity"
        dur="1000"
        fill="forwards"
        from="1"
        to="0"
        repeat="0"></a-animation>
    }
      //fade in
    {
     this.state.showHinter && 
      <a-animation 
        attribute="material.opacity"
        dur="1000"
        fill="forwards"
        from="0"
        to="1"
        repeat="0"></a-animation>
    }
  </AFrameEntity>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM