2016-12-01 79 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道具與相應值