天道酬勤,学无止境

Using props in React style attribute

(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
}
标签

评论

Most likely this.props.progess is not set to an appropriate value. Provide a good default for this case:

render() {

  const { progress = 0 } = this.props;

  return (
    <div style={{ width: progress + '%' }}></div>
  )
}

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

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐