-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
}
取決於'this.props.progress'的價值。 –
@JoeClay它無論是字符串或數字,你會得到'95%'。你的例子適用於我 –
@TheReason:是的,我只是想知道他是否得到了「undefined」或什麼東西。 –