如何在React中设置一组动态范围输入的值?

问题描述 投票:0回答:1

我有一个要遍历并创建范围输入的数组。

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同级的值?

reactjs input onchange
1个回答
0
投票

我知道了。我只需要在评级之外创建一个新组件,因此它具有自己的状态。

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()}
  );

}
© www.soinside.com 2019 - 2024. All rights reserved.