Last active
August 5, 2017 05:45
-
-
Save kenmori/acf54c6e0ebba1a55ad9a0f8a33c9aa0 to your computer and use it in GitHub Desktop.
【Reactのstateとpropsの違いが知りたい!(変更・更新の仕方等デモあり)】過去のReact初心者の自分にpropsとstateの違いを説明する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ParentComponent extends React.Component { | |
constructor(props){ | |
super(props) | |
this.state = { | |
name: "わたし" | |
}; | |
this.onChangeName = this.onChangeName.bind(this); | |
} | |
onChangeName(){ | |
const name = this.state.name === "あなた" ? "わたし" : "あなた"; | |
this.setState({ | |
name : name | |
}); | |
} | |
render(){ | |
return ( | |
<div> | |
<h1>親Componentです</h1> | |
//click押下で親で管理しているthis.state.name値が変わり子コンポーネントが再描画され、子が参照しているthis.props.nameが変わります | |
<ChildComponent name={this.state.name}></ChildComponent> | |
<a onClick={this.onChangeName}>click</a> | |
</div> | |
); | |
} | |
} | |
class ChildComponent extends React.Component { | |
constructor(props){ | |
super(props) | |
} | |
render(){ | |
return ( | |
<div> | |
<h2>題名(子Componentです)</h2> | |
{this.props.name}の未来 | |
</div> | |
); | |
} | |
} | |
React.render(<ParentComponent />, document.getElementById('container')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment