Add a State property to an Inline Style in React

邮差的信 提交于 2019-12-18 17:04:45

问题


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

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

I want to replace the width with a property from my state, although I'm not quite sure how to do it.

I tried:

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

Is this even possible?


回答1:


You can do it like this

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

Example




回答2:


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>
  );
}

:-)



来源:https://stackoverflow.com/questions/37827279/add-a-state-property-to-an-inline-style-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!