reactjs / reactjs/react.dev

Is it possible to remove the extra arrow function here?

Đang mở
#3,772 2 bình luận 2 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Ngôn ngữ chính
JavaScript
Star
11.8k
Fork
7.9k
Merge trung bình
1 ngày 11 giờ
Pull request đã merge (30 ngày)
11

Mô tả

Hi!
The tutorial has an example like this:

class Square extends React.Component {
  render() {
    return (
      <button
        className="square"
        onClick={() => this.props.onClick()}
      >
        {this.props.value}
      </button>
    );
  }
}

This component used in the Board component like this:

renderSquare(i) {
    return (
      <Square
        value={this.state.squares[i]}
        onClick={() => this.handleClick(i)}
      />
    );
  }

We have closed the context in a function that we pass to onClick in the Board component.
But why don't we just pass this.props.onClick to onClick in the Square component? Why are we using closures here if we already have the right context inside?

I wrote like this: (link to codepen)

class Square extends React.Component {
  render() {
    return (
      <button
        className="square"
        onClick={this.props.onClick}
      >
        {this.props.value}
      </button>
    );
  }
}

This works successfully

It is clear that the variant from the tutorial will also work. But further it says:

When we modified the Square to be a function component, we also changed onClick={() => this.props.onClick()} to a shorter onClick={props.onClick} (note the lack of parentheses on both sides).

So my variation only works in a functional component? But above it also worked in class components. I think this might confuse some people.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu bằng cách đọc các phần được liên kết trong tutorial về việc nâng state lên và các function component, sau đó so sánh hai ví dụ onClick cùng phần giải thích đi kèm. Kiểm tra xem ví dụ về class component có cần làm rõ sự khác nhau giữa việc truyền một callback và việc gọi nó hay không. Công việc được xem là hoàn tất khi tutorial giải thích rõ tại sao cả hai cách đều hoạt động và khi nào cách ngắn hơn là phù hợp.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
javascript, react
Lĩnh vực
documentation
Loại issue
Tài liệu
Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
35/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.