我有一个要遍历并创建范围输入的数组。
const ratings = [
{
title: 'Category One'
},
{
title: 'Category Two'
},
{
title: 'Category Three'
}
];
const renderRatings = ratings.map((rating, key) => {
return (
<div className="rating" key={key}>
<h3>{rating.title}</h3>
<div className="rating__num">0</div>
<input className="rating__range" type="range" min="0" max="10" />
</div>
);
});
我将如何更新每个rating__num
以反映其rating__range
同级的值?
我知道了。我只需要在评级之外创建一个新组件,因此它具有自己的状态。
function Rating(props) {
const [ratingValue, setRatingValue] = useState(0);
return (
<div className="rating" key={key}>
<h3>{rating.title}</h3>
<div className="rating__num">{ratingValue}</div>
<input
className="rating__range"
type="range"
min="0"
max="10"
onChange={(e) => setRatingValue(e.currentTarget.value)}
/>
</div>
):
}
function MyComponent(props) {
const renderRatings = ratings.map((rating, key) => {
return (
<Rating key={key} rating={rating} />
);
});
return (
{renderRatings()}
);
}