Skip to content

Instantly share code, notes, and snippets.

@kenmori
Last active August 5, 2017 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenmori/acf54c6e0ebba1a55ad9a0f8a33c9aa0 to your computer and use it in GitHub Desktop.
Save kenmori/acf54c6e0ebba1a55ad9a0f8a33c9aa0 to your computer and use it in GitHub Desktop.
【Reactのstateとpropsの違いが知りたい!(変更・更新の仕方等デモあり)】過去のReact初心者の自分にpropsとstateの違いを説明する
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