05月02, 2018

React学习之旅 (07) -- children & 父子组件通信 & refs深入

this.props.children 里面就是组件里的内容,栗子:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</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="root"></div>
    <script type="text/babel">
        const Component = React.Component;
        class Child extends Component {
            render() {
                let {title, children} = this.props;
                return (<div>我是子组件, {title} {children}</div>)
            }
        }

        let List = ({arr})=>(<div>
            { arr.map( (item, index) => <p key={index}>{index}. {item}</p> ) }
        </div>)

        class Parent extends Component {
            render() {
                return (<div>
                    <h2>欢迎来捡漏儿</h2>
                    <Child title="父组件传过来的东西">
                        <List arr={['aaa', 'bbb', 'ccc']} />
                    </Child>
                </div>);
            }
         }

        ReactDOM.render(<Parent />,
        document.getElementById('root'));
    </script>
  </body>
</html>

关于通信:

父 --> 子:通过设置属性,props方式

子 --> 父: 通过回调函数

关于refs:

官方已经不推荐 this.refs.xxx 形式,推荐回调函数形式:

<div ref={ (con) => this.con = con }></div>

本文链接:http://www.laijianlou.top/post/react-07.html

-- EOF --

Comments