react:method内部でこの方法を使用する様々な方法
方法bindをイベントハンドラの横に貼り付ける
class Component extends React.Component {
state = {
count : 0,
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.click.bind(this)}> //this 사용 선언
클릭
</button>
</div>
)
}
click() {
this.setState((state) => ({...state,count:state.count+1}));
}
}
方法コンストラクション関数(props)を使用してbind(this)をメソッドに貼り付けます. class Component extends React.Component {
state = {
count : 0,
}
constructor(props) {
super(props);
this.click = this.click.bind(this); // this 사용 선언
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.click}>
클릭
</button>
</div>
)
}
click() {
this.setState((state) => ({...state,count:state.count+1}));
}
}
方法methodを関数に変換(推奨)class Component extends React.Component {
state = {
count : 0,
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.click}>
클릭
</button>
</div>
)
}
click =() => { // this 사용가능
this.setState((state) => ({...state,count:state.count+1}));
}
}
個人的には方法3というコードが少なくても便利だと思います!Reference
この問題について(react:method内部でこの方法を使用する様々な方法), 我々は、より多くの情報をここで見つけました https://velog.io/@whdms3368/React-기본기-익히기-method-내부-this-사용하는-여러가지-방법テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol