一、react的props用以父組件向子組件傳遞參數
如下例所示:
1、propTypes用於驗證props的類型。
2、getDefaultProps用於設定props的預設值。
3、在父組件中通過屬性的方式,傳遞給子組件<SubMessage messages={this.state.subMessages}/>,子組件中使用this.props.messages得到父組件傳遞的messages值。
<!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 : [ '我會寫代碼', '也會撒嬌', '老闆叫我回去搬磚' ] }; }, render: function(){ return ( <div> <SubMessage messages={this.state.subMessages}/> </div> ); } }); var SubMessage = React.createClass({ propTypes:{ messages: React.PropTypes.array.isRequired, }, getDefaultProps: function(){ return { messages: ['預設的子訊息'] }; }, render: function(){ var subMsg = []; this.props.messages.forEach(function(val, index){ subMsg.push( <p>碼農說:{val}</p> ); }) return ( <div>{subMsg}</div> ); } }); React.render( <MessageBox />, document.getElementById('app') ); </script></body></html>
二、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>