2016-06-15 60 views
1

我有了這樣一個內嵌式的一個反應元素:(簡略版)國家屬性添加到內聯樣式在陣營

 <div className='progress-bar' 
      role='progressbar' 
      style={{width: '30%'}}> 
     </div> 

我想從我的狀態屬性以替換寬度,雖然我不太清楚如何去做。

我想:

 <div className='progress-bar' 
      role='progressbar' 
      style={{{width: this.state.percentage}}}> 
     </div> 

這甚至可能嗎?

回答

2

你可以像下面這樣做

style={ { width: `${ this.state.percentage }%` } } 

Example

+0

感謝你,沒有的伎倆! – lost9123193

0

是它可以檢查以下

class App extends React.Component { 

    constructor(props){ 
    super(props) 
    this.state = { 
     width:30; //default 
    }; 
    } 


    render(){ 

//when state changes the width changes 
const style = { 
    width: this.state.width 
} 

    return(
    <div> 
    //when button is clicked the style value of width increases 
     <button onClick={() => this.setState({width + 1})}></button> 
     <div className='progress-bar' 
      role='progressbar' 
      style={style}> 
     </div> 
    </div> 
); 
} 

:-)

+0

您是否使用工具自動添加分號? – stackdave