我有一个具有内联样式的react元素:(缩短版本)
<div className='progress-bar'
role='progressbar'
style={{width: '30%'}}>
</div>
我想用我的州的属性替换宽度,虽然我不太清楚如何做到这一点。
我试过了:
<div className='progress-bar'
role='progressbar'
style={{{width: this.state.percentage}}}>
</div>
这甚至可能吗?
答案 0 :(得分:8)
答案 1 :(得分: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>
);
}
: - )