react--props

前端之家收集整理的这篇文章主要介绍了react--props前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、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>
原文链接:https://www.f2er.com/react/301842.html

猜你在找的React相关文章