React.js props
今回はpropsをやります。前回のstateはコンポーネント内でデータを共有しましたが、propsはコンポーネント外でデータを連携します。データ連携
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>React Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="hello"></div>
<script type="text/babel">
var Hello = React.createClass({
getInitialState: function() {
return {msgH: "Hello"};
},
render: function() {
return (
<World message={this.state.msgH} />
);
}
});
var World = React.createClass({
getInitialState: function() {
return {msgW: "World!!"};
},
render: function() {
return (
<h1>{this.props.message + " " + this.state.msgW}</h1>
);
}
});
ReactDOM.render(
<Hello />,
document.getElementById('hello') );
</script>
</body>
</html>
実行イメージ
props
別コンポーネント間でデータを連携するにはpropsを使用します。コンポーネントの属性で指定したデータをpropsで取得することができます。
親コンポーネント
return (
<World message={this.state.msgH} />
);
子コンポーネント
return (
<h1>{this.props.message + " " + this.state.msgW}</h1>
);
メソッド連携
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>React Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="hello"></div>
<script type="text/babel">
var Hello = React.createClass({
showMsg : function(msg){
alert(msg);
},
render: function() {
return (
<World message={this.showMsg} />
);
}
});
var World = React.createClass({
render: function() {
this.props.message("Hello World!!");
return (
<h1>OK !!</h1>
);
}
});
ReactDOM.render(
<Hello />,
document.getElementById('hello') );
</script>
</body>
</html>
propsを使うとメソッドも連携できます。子コンポーネント側から親コンポーネントのメソッドを実行できます。 ページのトップへ戻る