2016-11-06 21 views
1

我的反應如下代碼。樣式對應於在頂部導入的標記的名稱。Const在反應中不存在

import {markerColored, markerUnColored, markerDefault} from './markers.js'; 

    .... 

    render() { 
    if(this.props.colored){ 
     const style = markerColored; 
    }else if(this.props.unSelected){ 
     const style = markerUnColored; 
    }else{ 
     const style = markerDefault; 
    } 

    return (
     <div className=" hint hint--html hint--info hint--top " style={style}> 
      {this.renderMarkerIcon()} 
     </div> 
    ); 
} 
} 

當我運行上面下面,我得到的錯誤:

Uncaught ReferenceError: style is not defined  

但是,如果我這樣做,我沒有得到任何錯誤:

render() { 

    const style = this.props.colored? markerColored : markerUnColored 

    return (
     <div className=" hint hint--html hint--info hint--top " style={style}> 
      {this.renderMarkerIcon()} 
     </div> 
    ); 

的問題是我有3種我想使用的樣式。爲什麼頂級代碼告訴我const函數在通過條件循環時不存在?我錯過了一些微不足道的東西嗎?

+1

'const'被阻塞作用域。 'style'不能在'if'塊之外訪問。 –

回答

3

const總是特定於範圍。這裏的範圍是ifelse。之後它將是未定義的。

試試這個

let style = markerDefault 
if(this.props.colored){ 
    style = markerColored; 
}else if(this.props.unSelected){ 
    style = markerUnColored; 
} 
+0

我明白了,這很有道理,謝謝! – lost9123193