Add a State property to an Inline Style in React

前端 未结 2 665
逝去的感伤
逝去的感伤 2021-01-03 02:36

I have a react element that has an inline style like this: (Shortened version)

      
相关标签:
2条回答
  • 2021-01-03 03:18

    You can do it like this

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

    Example

    0 讨论(0)
  • 2021-01-03 03:32

    yes its possible check below

    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 讨论(0)
提交回复
热议问题