2016-10-04 40 views
0

我想了解一些本機反應,但我正在努力解決與類變量有關的問題。這是我的代碼(我沒有粘貼整個之一,因爲它是很長,但是這應該給我的問題的想法):類變量中的道具是undefined

class VideoScreen extends Component { 
static _toHHMMSS(time) { 
    var sec_num = parseInt(time, 10); // don't forget the second param 
    var hours = Math.floor(sec_num/3600); 
    var minutes = Math.floor((sec_num - (hours * 3600))/60); 
    var seconds = sec_num - (hours * 3600) - (minutes * 60); 

    if (hours < 10) { 
     hours = "0" + hours; 
    } 
    if (minutes < 10) { 
     minutes = "0" + minutes; 
    } 
    if (seconds < 10) { 
     seconds = "0" + seconds; 
    } 
    return hours + ':' + minutes + ':' + seconds; 
} 

_currentTime = <View refreshing> 
    <Text>{VideoScreen._toHHMMSS(this.props.currentTime)} 
    </Text> 
</View>; 

render() { 
    return (
     <View refreshing> 
      {this._currentTime} 
     </View> 
    ) 
} 

}

不幸道具是變量中未定義「_currentTime 」。如果我直接將視圖移動到render方法中,它可以正常工作(我需要它在一個單獨的變量中,因爲我需要根據布爾值隱藏它並創建變量使代碼更具可讀性)。我是否必須像使用方法一樣將變量綁定到類,或者我是否在做其他問題?

回答

0

問題是this沒有綁定。我不確定你是否可以綁定一個變量,但你可以用一種方法實現你想要的結果:

class VideoScreen extends Component { 
    constructor(props) { 
     super(props); 
     this._currentTime = this._currentTime.bind(this); 
    } 

    render() { 
     return (
      <View refreshing> 
       {this._currentTime()} 
      </View> 
     ) 
    } 

    _currentTime() { 
     return (
      <View refreshing> 
       <Text>{VideoScreen._toHHMMSS(this.props.currentTime)} 
       </Text> 
      </View> 
     ); 
    } 
} 
+0

你好,喬爾戈斯,謝謝你的回覆。這也是我的想法,但不幸的是,它不可能綁定變量,至少不可能像使用bind()方法那樣建議:-( –

+0

等一秒,所以你建議把變量變成一個函數...我會嘗試它,看看它的工作。同時感謝! –

+0

它的工作就像一個魅力,謝謝!唯一的事情是,你需要執行該函數通過調用{this._currentTime()}內渲染方法;-) –