在 React 中向内联样式添加状态 属性
Add a State property to an Inline Style in React
我有一个具有内联样式的 React 元素,如下所示:(简化版)
<div className='progress-bar'
role='progressbar'
style={{width: '30%'}}>
</div>
我想用我所在州的 属性 替换宽度,但我不太确定该怎么做。
我试过了:
<div className='progress-bar'
role='progressbar'
style={{{width: this.state.percentage}}}>
</div>
这可能吗?
你可以这样做
style={ { width: `${ this.state.percentage }%` } }
是的,可以在下面检查
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>
);
}
:-)
我有一个具有内联样式的 React 元素,如下所示:(简化版)
<div className='progress-bar'
role='progressbar'
style={{width: '30%'}}>
</div>
我想用我所在州的 属性 替换宽度,但我不太确定该怎么做。
我试过了:
<div className='progress-bar'
role='progressbar'
style={{{width: this.state.percentage}}}>
</div>
这可能吗?
你可以这样做
style={ { width: `${ this.state.percentage }%` } }
是的,可以在下面检查
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>
);
}
:-)