programing tip

렌더링시 내 onClick이 호출되는 이유는 무엇입니까?

itbloger 2020. 10. 12. 07:19
반응형

렌더링시 내 onClick이 호출되는 이유는 무엇입니까? -React.js


내가 만든 구성 요소가 있습니다.

class Create extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    var playlistDOM = this.renderPlaylists(this.props.playlists);
    return (
      <div>
        {playlistDOM}
      </div>
    )
  }

  activatePlaylist(playlistId) {
    debugger;
  }

  renderPlaylists(playlists) {
    return playlists.map(playlist => {
      return <div key={playlist.playlist_id} onClick={this.activatePlaylist(playlist.playlist_id)}>{playlist.playlist_name}</div>
    });
  }
}

function mapStateToProps(state) {
  return {
    playlists: state.playlists
  }
}

export default connect(mapStateToProps)(Create);

I되면 render이 페이지는 activatePlaylist각각라고 playlist않은 내 map. 내가 bind activatePlaylist좋아 한다면 :

activatePlaylist.bind(this, playlist.playlist_id)

익명 함수를 사용할 수도 있습니다.

onClick={() => this.activatePlaylist(playlist.playlist_id)}

그러면 예상대로 작동합니다. 왜 이런 일이 발생합니까?


함수 onClick 대한 참조전달해야합니다. 이렇게 activatePlaylist( .. )하면 함수를 호출하고 onClick에서 반환 된 값으로 전달합니다 activatePlaylist. 다음 세 가지 옵션 중 하나를 사용할 수 있습니다.

1 . 사용.bind

activatePlaylist.bind(this, playlist.playlist_id)

2 . 화살표 기능 사용

onClick={ () => this.activatePlaylist(playlist.playlist_id) }

3 . 또는 반환 함수activatePlaylist

activatePlaylist(playlistId) {
  return function () {
     // you code 
  }
}

이 동작은 React가 클래스 기반 구성 요소의 릴리스를 발표했을 때 문서화되었습니다.

https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html

자동 바인딩

React.createClass has a built-in magic feature that bound all methods to this automatically for you. This can be a little confusing for JavaScript developers that are not used to this feature in other classes, or it can be confusing when they move from React to other classes.

Therefore we decided not to have this built-in into React's class model. You can still explicitly prebind methods in your constructor if you want.


I know this post is a few years old already, but just to reference the latest React tutorial/documentation about this common mistake (I made it too) from https://reactjs.org/tutorial/tutorial.html:

Note

To save typing and avoid the confusing behavior of this, we will use the arrow function syntax for event handlers here and further below:

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

onClick = {() => alert ( 'click')}을 사용하여 함수를 onClick 소품으로 전달하는 방법을 확인하세요. React는 클릭 후에 만이 함수를 호출합니다. () =>을 잊어 버리고 onClick = {alert ( 'click')}을 쓰는 것은 흔한 실수이며 구성 요소가 다시 렌더링 될 때마다 경고를 발생시킵니다.


메서드를 전달하는 방식 this.activatePlaylist(playlist.playlist_id)은 즉시 메서드를 호출합니다. 메서드의 참조를 onClick이벤트에 전달해야합니다 . 아래 언급 된 구현 중 하나를 따라 문제를 해결하십시오.

1.
onClick={this.activatePlaylist.bind(this,playlist.playlist_id)}

여기서 bind 속성은 컨텍스트와 인수 this.activatePlaylist를 전달 하여 메서드 의 참조를 만드는 데 사용됩니다.thisplaylist.playlist_id

2.
onClick={ (event) => { this.activatePlaylist.(playlist.playlist_id)}}

이렇게하면 사용자 클릭 동작에서만 트리거되는 onClick 이벤트에 함수가 연결됩니다. 이 코드가 예상되면 this.activatePlaylist메서드가 호출됩니다.

참고URL : https://stackoverflow.com/questions/34226076/why-is-my-onclick-being-called-on-render-react-js

반응형