react props for parent components to pass parameters to subassemblies
As shown in the following example:
1, Proptypes is used to verify the type of props.
2, Getdefaultprops is used to set the default value of props.
3, in the parent component through the way of the property, passed to the subassembly <submessage Messages={this.state.submessages}/> The messages value passed by the parent component is obtained using This.props.messages in the subassembly.
<! DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title> this </ title>
<script type = "text / javascript" src = "bower_components / react / react.js"> </ script>
<script type = "text / javascript" src = "bower_components / react / JSXTransformer.js"> </ script>
</ head>
<body>
<div id = "app"> </ div>
<script type = "text / jsx">
var MessageBox = React.createClass ({
getInitialState: function () {
return {
subMessages: [
'I will write code',
'Coquettish',
'The boss told me to go back and move the bricks'
]
};
},
render: function () {
return (
<div>
<SubMessage messages = {this.state.subMessages} />
</ div>
);
}
});
var SubMessage = React.createClass ({
propTypes: {
messages: React.PropTypes.array.isRequired,
},
getDefaultProps: function () {
return {
messages: ['default child message']
};
},
render: function () {
var subMsg = [];
this.props.messages.forEach (function (val, index) {
subMsg.push (
<p> Code farmer said: {val} </ p>
);
})
return (
<div> {subMsg} </ div>
);
}
});
React.render (
<MessageBox />,
document.getElementById ('app')
);
</ script>
</ body>
</ html>
Second、this.props.children
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo2</title>
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/jsx">
var Comp = React.createClass({
render: function(){
console.log( React.Children.map);
var childComps = React.Children.map(this.props.children,function(child){
return <li>{child}</li>;
})
return (
<ol>
{childComps}
</ol>
);
}
});
ReactDOM.render(
<Comp>
<span>hello</span>
<span>nihao</span>
</Comp>,
document.getElementById('app')
);
</script>
</body>
</html>