Star.Rating组件中this.handleSetRating(i + 1)的工作方式是什么?

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

这是StarRating组件=>

class StarRating extends Component {
  state = {
    rating: 0,
  };
  renderStars = () => {
    let stars = [];
    let maxRating = 5;

    for (let i = 0; i < maxRating; i++) {
      stars.push(
        <Star
          isSelected={this.state.rating > i}
          setRating={() => this.handleSetRating(i + 1)}
          key={i}
        />
      );
    }
    return stars;
  };
  handleSetRating = (rating) => {
    if (this.state.rating === rating) {
      this.setState({ rating: 0 });
    } else {
      this.setState({ rating });
    }
  };

  render() {
    return <ul className="course--stars">{this.renderStars()}</ul>;
  }
}

这是Star组件=>

const Star = (props) => (
  <li 
    className={props.isSelected ? "selected" : null} 
    onClick={props.setRating}>
    <svg x="0px" y="0px" viewBox="0 0 16 15" className="star">
      <path
        d="M8.5,0.3l2,4.1c0.1,0.2,0.2,0.3,0.4,0.3l4.6,0.7c0.4,0.1,0.6,0.6,0.3,0.9l-3.3,3.2c-0.1,0.1-0.2,0.3-0.2,0.5l0.8,4.5
      c0.1,0.4-0.4,0.8-0.8,0.6l-4.1-2.1c-0.2-0.1-0.3-0.1-0.5,0l-4.1,2.1c-0.4,0.2-0.9-0.1-0.8-0.6l0.8-4.5c0-0.2,0-0.4-0.2-0.5L0.2,6.2
      C-0.2,5.9,0,5.4,0.5,5.3L5,4.7c0.2,0,0.3-0.1,0.4-0.3l2-4.1C7.7-0.1,8.3-0.1,8.5,0.3z"
      />
    </svg>
  </li>
);

当onClick函数在Star组件上调用它时,循环内的this.handleSetRating()函数如何工作?


精确地说,当for循环运行时,Star组件上的setRating()是否得到立即解析并调用this.handleSetRating(i + 1)] >>;发生这种情况将导致无限循环,或者它使用closure记住每次迭代后的ith值,因此当onClick on Star组件调用它时,它使用closure来使用i值。

这是StarRating组件=>类StarRating扩展了Component {state = {rating:0,}; renderStars =()=> {让stars = [];让maxRating = 5;为(...

javascript html reactjs closures
1个回答
0
投票

...或者它使用闭包来记住每次迭代后的第i个值,因此当Star组件上的onClick调用它时,它使用闭包来使用i

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