
event (์ด๋ฒคํธ)
- ์นด๋ฉ ์ผ์ด์ค๋ก ์์ฑ๋๋ฉฐ, html ์์ onclick์ React์์ onClick์ผ๋ก ์์ฑํ๋ค.
- ํธ๋ค๋ฌ ํจ์๋ ์ปดํฌ๋ํธ ๋ด์์ ์์ฑ๋๋ฉฐ, ์ต๋ช ํจ์๋ก๋ ์์ฑํ ์ ์๋ค.
- ์ต๋ช ํจ์ ๋ด์์ this๊ฐ ์๋ฌด๊ฒ๋ ๊ฐ๋ฆฌํค์ง ์์ผ๋ฏ๋ก bind ํจ์๋ฅผ ์ฌ์ฉํ์ฌ this๋ฅผ ์ง์ ํด์ค๋ค.
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
buttonName = '์ ์ฅ'
};
}
handleClick() {
console.log(this.state.buttonName, '๋ฒํผ์ด ํด๋ฆญ๋์์ต๋๋ค.');
}
render() {
return (
<button onClick={this.handleClick}>ํด๋ฆญ</button>
<button onClick={function() {
console.log(this.state.buttonName, '๋ฒํผ์ด ํด๋ฆญ๋์์ต๋๋ค.');
}.bind(this)}
>ํด๋ฆญ</button>
);
}
}
์ปดํฌ๋ํธ ๊ฐ ์ด๋ฒคํธ ์ฌ์ฉ
- ์์ -> ๋ถ๋ชจ ์ปดํฌ๋ํธ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๊ณ ์ ํ ๋ event๋ฅผ ์ฌ์ฉํ๋ค.
- props์ ์์ฑ์ผ๋ก ์ด๋ฒคํธ๋ฅผ ์ง์ ํ ์ ์๊ณ , ํ์ ์ปดํฌ๋ํธ์์ ์ด๋ฒคํธ๊ฐ ์คํ๋๋๋ก ํ ์ ์๋ค.
- ์ด๋ฒคํธ ์ต๋ช ํจ์์ ์ฒซ๋ฒ์งธ default ํ๋ผ๋ฏธํฐ๋ก ์ด๋ฒคํธ๊ฐ ๋์ด์จ๋ค.
- bind ํจ์ this ํ๋ผ๋ฏธํฐ ์ธ์ ๋ค๋ฅธ ๊ฑธ ์ง์ ํ๋ฉด default ํ๋ผ๋ฏธํฐ์ธ ์ด๋ฒคํธ๋ ๋ค๋ก ๋ฐ๋ ค๋๋ค.
// ๋ถ๋ชจ ์ปดํฌ๋ํธ
import React, { Component } from 'react';
import ChildComponent './ChildComponent';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
title = '';
}
}
render() {
return (
<ChildComponent onCustomEvent={function(_title) {
this.state.title = _title;
console.log(_title);
}.bind(this)}></ChildComponent>
);
}
}
// ์์ ์ปดํฌ๋ํธ
import React, { Component } from 'react';
class ChildComponent extends Component {
constructor() {
super(props);
this.state = {
contents: [
{ id: 1, title: 'HTML' },
{ id: 2, title: 'CSS' },
{ id: 3, title: 'JavaScript' }
]
}
}
render() {
var i = 0;
var lists = [];
while (i < this.state.contents.length) {
var content = this.state.contents[i];
lists.push(
<li key={content.id}>
<a onClick={
function(_title, e) {
e.preventDefault();
this.props.onCustomEvent(_title);
}.bind(this, content.title)
}>{title}</a>
</li>
);
i = i+1;
}
return (
<ul>
{lists}
</ul>
);
}
}
export default ChildComponent;
๋ฐ์ํ
'Frontend > React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
React | ์๋ช ์ฃผ๊ธฐ ๋ฉ์๋(Lifecyle Methods) (0) | 2023.11.28 |
---|---|
React | ๊ฐ์ฒด ํ์ State ์ ๋ฐ์ดํธ (0) | 2023.11.27 |
React | ๋ฐฐ์ด ํ์ State ์ ๋ฐ์ดํธ (1) | 2023.11.24 |
React | ๋ณ์ vs State (2) | 2023.11.23 |
React | Props (์์ฑ), State (์ํ) ์ ๋ํด์ (0) | 2023.11.17 |