2016-12-01 78 views
-1

(我使用JSX与ES6语法)在使用道具阵营style属性

这工作:

render() { 
    return (
    <div style={{ width: '95%' }}></div> 
) 
} 

这不起作用:(为什么不呢?)编辑:它实际上做的工作

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

编辑:

它可以工作,但样式值必须是有效的值,否则会返回错误。

我使用状态来创建样式对象,并用构造函数中的正则表达式清除属性,所以它不会因错误的值而再次出错。这是我的解决方案:

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 
} 
+0

取决于'this.props.progress'的价值。 –

+0

@JoeClay它无论是字​​符串或数字,你会得到'95%'。你的例子适用于我 –

+1

@TheReason:是的,我只是想知道他是否得到了“undefined”或什么东西。 –

回答

0

最有可能的this.props.progess未设置为适当的值。为此情况提供良好的默认设置:

render() { 

    const { progress = 0 } = this.props; 

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

您的示例按预期工作。

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。只要确保你不要忘记设置progress道具与相应值