简体   繁体   中英

React-Semantic-UI Rating onRate() undefined value

I want to create a star-rating system in ReactJS. For this purpose, I am using React-Semantic-UI Rating. However, at the first click, it gives the state's initial value (which is a 0) and at the next clicks, it gives undefined values. I am glad if someone explains it in a react functional component but other methods are also acceptable:)

import React, { useState } from 'react';
import {
  Container,
  Rating
} from 'semantic-ui-react';

    function App() {
      const [rating, setRating] = useState(0);
    ​
      function handleChangeOnRate(e) {
        e.preventDefault();
        setRating(e.target.value);
      }
    ​
      return (
        <div className='App'>
          <Container>
            <Rating
              value={rating}
              onRate={(e) => {
                handleChangeOnRate(e);
                console.log(rating);
              }}
              maxRating={5}
              icon='star'
              size='huge'
            />
          </Container>
        </div>
      );
    }
    ​
    export default App;

I had a look in the documentation for Semantic UI React.

It seems like the rating is passed as an object property in the second parameter of the onRate callback. So you should be able to do this to get the rating.

<Rating
  value={rating}
  onRate={handleChangeOnRate}
  maxRating={5}
  icon='star'
  size='huge'
/>

And then handle it like this.

function handleChangeOnRate(e, { rating }) {
  e.preventDefault();
  setRating(rating);
}

The current value of Rating is not 'value' but 'rating'. This is how you can write your onRate handler:

handleChangeOnRate= (e, { rating }) => {
    e.preventDefault();
    setRating(rating)
}

And replace value with rating in your render function:

       <Rating
          rating={rating}
          ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM