(I am using JSX with ES6 syntax)
This works:
render() {
return (
<div style={{ width: '95%' }}></div>
)
}
This doesn't work: (why not?) Edit: It actually does work
render() {
return (
<div style={{ width: this.props.progress + '%' }}></div>
)
}
Edit:
It works but the style value has to be a valid value else it will return the error.
I use the state to create the style object and clean out the property with a regular expression in the constructor, so it will not be error-ing again because of invalid values. Here is my solution:
import React, { Component, PropTypes } from 'react'
export default class ProgressBar extends Component {
constructor(props) {
super(props)
let progress = +props.progress.replace(/[^0-9]/g, '') || 50
this.state = {
style: {
width: progress + '%'
}
}
}
render() {
return (
...
<div className="progress-bar" role="progressbar" aria-valuenow={ this.state.progress } style={ this.state.style }></div>
...
)
}
}
ProgressBar.propTypes = {
progress: PropTypes.string.isRequired
}
评论
Your example works as you ex
Your example works as you expected.
class Example extends React.Component {
render(){
const style = {
width: this.props.progress + '%',
backgroundColor : 'red'
}
return <div style={style}>
Hello
</div>
}
}
React.render(<Example progress={10}/>, document.getElementById('container'));
Fiddle. Just make sure that you dont forget to set progress
prop with coresponding value
Update 2021 (Functional Component)
const Example = (props) {
const style = {
width: props.progress + '%',
backgroundColor : 'red'
}
return (
<div style={style}>Hello</div>
);
}
React.render(<Example progress={10}/>, document.getElementById('container'));
Most likely
this.props.progess
is not set to an appropriate value. Provide a good default for this case: