props.children属性

props.children 就是我们在调用组件时,填充在组件标签里面的内容。

如果我们在使用组件的时候,内部有标签怎么获取?

<div id="app"></div>
    <script type="text/babel">
        class Person extends React.Component{
            render (){
                console.log(this)
                return <div>
                        <p>hello</p>
                        <p>{this.props.name}</p>
                    </div>
            }
        }

        ReactDOM.render(<Person name="小明"><h3>word</h3></Person>,document.getElementById("app"))
    </script>

 此时我们在浏览器输出可以看到

 

 

 此时我们可以通过props.children来获取

 class Person extends React.Component{
            render (){
                console.log(this)
                return <div>
                        <p>hello</p>
                        <p>{this.props.name}</p>
                        {this.props.children}
                    </div>
            }
        }

props 的注意事项

props 用于传递数据,这个数据是一个单向传递,从根节点组件向它的子孙组件传递,逆向传递是不被允许的

单向数据流

  • react 中关于数据的流动有一条原则,就是单向数据流,自顶向下,从父组件到子组件
  • 单向数据流特性要求我们共享数据要放置在上层组件中
  • 子组件通过调用父组件传递过来的方法更改数据
  • 当数据发送更改时,react会重新渲染组件
  • 单向数据流时组件之间的数据流动变得可预测,使定位错位变得简单

 

子组件如果想要修改根节点组件的状态,需要根节点组件给子孙组件传递事件方法

    <div id="app"></div>
    <script type="text/babel">
        //props事件传递
        //子组件

            click(){
                console.log(this)  //undefined
                // 为了在回调中使用 `this`,这个绑定是必不可少的
                this.props.onDJ()
                
            }
            render (){
                console.log(this)   //在props中获取 DJ属性
                return <div>
                               <button onClick={this.click}>点击</button>
                    </div>
            }
        }
        //根组件
        class App extends React.Component{
            fun(){
                console.log('我是父组件的方法fun')
            }
            render (){
                return <div>
                       <Person onDJ={this.fun}></Person>
                    </div>
            }
        }
        ReactDOM.render(<App></App>,document.getElementById("app"))
    </script>

 此时在click函数中获取不到this而报错

 

 

 使用这种方法可以解决this问题

<button onClick={this.props.onDJ}>点击</button> 

 

 

 但是这种写法并不推荐,虽然可以解决,但是每个事件毕竟都有构造函数

我们可以使用构造函数解决

 class Person extends React.Component{
            constructor(){
                super();
                this.click=this.click.bind(this)
            }
            click(){
                console.log(this)  //undefined
                // 为了在回调中使用 `this`,这个绑定是必不可少的
                this.props.onDJ()
                
            }
            render (){
                console.log(this)   //在props中获取 DJ属性
                return <div>
                        <button onClick={this.click}>点击</button>
                    </div>
            }
        }

 

 

 

事件函数中this问题

  • 事件函数中的this 不是我们的组件实例对象 而是undefined

  • 在构造器constructor里我们需要对事件函数进行this绑定,否则函数中的this都是undefine

通过 props.children 属性可以获取到在调用组件时填充到组件标签内的内容

 

posted @ 2021-11-15 22:06  keyeking  阅读(549)  评论(0编辑  收藏  举报