[TIL 32] React | State, Props
State
構成部品の内部では、構成部品のステータス値を変更できます.
とにかく、
構成部品のステータス値を変更できます\
複数の構成部品を使用すると、それぞれの状態になります.
クラス構成部品でstateを定義します.
class App extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
}
// 같은 코드지만 배우는 입장에서는 constructor안에 써주는게 좋다고 한다!
//state = {
// count: 0
//};
add = () => {
this.state.count = 1;
};
minus = () => {
this.state.count = -1;
};
render(){
return (
<div>
<h1>The number is : {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
)
}
}
add
、minus
関数はcountの値を変更していますが、結果は機能しません.どうして行動しないの?
reactはrender関数をリフレッシュしないからです.
stateステータスが変更されるたびにreactがrender関数を呼び出して変更する場合はsetStateを使用します.
setState
ステータスオブジェクトの更新を実行する関数
class App extends React.Component {
state = {
count: 0
};
add = () => {
this.setState(current => ({count: current.count + 1}));
// this.setState({count: this.state.count + 1});
// -> 안좋은예 (current로 현재의 상태를 불러와서 사용하도록 하자.)
};
minus = () => {
this.setState({
count: this.state.count - 1
});
};
render(){
return (
<div>
<h1>The number is : {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
)
}
}
Props
親コンポーネントから渡されたデータを持つオブジェクト.
propsにより、ステータスのステータス値、イベントハンドラを親コンポーネントからサブコンポーネントに渡すことができます.
부모 컴포넌트에서 자식 컴포넌트에게 state, 함수 전달
자식 컴포넌트에서 부모의 props를 받음
Props vs State
propsは関数パラメータのようにコンポーネントに渡され、stateは関数で宣言された変数のようにコンポーネントで管理されます.
Reference
この問題について([TIL 32] React | State, Props), 我々は、より多くの情報をここで見つけました https://velog.io/@nsunny0908/TIL-32-React-props-stateテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol