【问题标题】:Add a State property to an Inline Style in React在 React 中将 State 属性添加到内联样式
【发布时间】:2016-10-16 02:05:31
【问题描述】:

我有一个具有如下内联样式的 react 元素:(缩短版)

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

我想用我所在州的属性替换宽度,尽管我不太确定该怎么做。

我试过了:

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

这可能吗?

【问题讨论】:

    标签: css reactjs styles state


    【解决方案1】:

    你可以这样做

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

    Example

    【讨论】:

      【解决方案2】:

      是的,可以在下面检查

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

      :-)

      【讨论】:

      • 你有没有使用工具自动添加分号?
      • 你可以在 vscode 中设置 eslint on save 来做到这一点
      猜你喜欢
      • 2021-10-03
      • 2023-04-07
      • 1970-01-01
      • 2020-11-18
      • 2020-04-30
      • 1970-01-01
      • 2021-11-09
      • 2019-01-29
      • 1970-01-01
      相关资源
      最近更新 更多