我编写了一个React组件,该组件呈现评级并用星号对其进行可视化。但是我必须为此使用危险的SetInnerHTML。我该如何重写具有更好代码风格的组件,而又不必危险地设置SetInnerHTML?谢谢您的帮助。
export default class BookRating extends React.Component {
renderStars = () => {
let result = '';
for(let i=1; i<=5; i++) {
this.props.rating >= i
? result += '<div class="fa fa-star checked"></div>'
: result += '<div class="fa fa-star"></div>'
}
return result;
}
render () {
return (
<div className="rating" dangerouslySetInnerHTML={{ __html: this.renderStars() }} />
);
}
}
答案 0 :(得分:7)
您可以使用数组而不是字符串来呈现多个元素:
export default class BookRating extends React.Component {
renderStars = () => {
let result = [];
for(let i=1; i<=5; i++) {
this.props.rating >= i
? result.push(<div key={i} class="fa fa-star checked"></div>)
: result.push(<div key={i} class="fa fa-star"></div>'
}
return result;
}
render () {
return (
<div className="rating">{this.renderStars()}</div>
);
}
}
正如Quentin和Emile所指出的,您可以像这样写一行代码:
renderStars = () => Array(5).fill(0).map(_, i => <div className={`fa fa-star${this.props.rating > i ? ' checked' : ''}`}/>)
答案 1 :(得分:1)
我做了类似的事情,也支持半星,并在其余位置显示“空”星(例如3.5颗星将显示3个全星,1个半星和1个空星):
const Rating = ({ rating }) => {
rating = Math.round(rating * 2) / 2
const fullStars = Math.floor(rating)
const halfStars = rating - fullStars > 0.2 ? 1 : 0
const emptyStars = 5 - fullStars - halfStars
return (
<div css={{ whiteSpace: "nowrap", ".fa": { color: "yellow" } }}>
{[...Array(fullStars)].map((_, index) => (
<span key={`f-${index}`} className="fa fa-star" />
))}
{[...Array(halfStars)].map((_, index) => (
<span key={`h-${index}`} className="fa fa-star-half-o" />
))}
{[...Array(emptyStars)].map((_, index) => (
<span key={`o-${index}`} className="fa fa-star-o" />
))}
</div>
)
}