React學習08_組件間的傳值與this的綁定

React學習08_組件間的傳值與this的綁定

父子傳值

  1. 父組件在使用子組件時,給它的屬性傳入想給它的數據
  2. 子組件通過 this.props.屬性名 可以獲取該數據

子向父傳值

  1. 父組件向子組件傳入一個帶參數的方法
  2. 子組件通過向這個方法傳入自己的數據,在父組件觸發該方法,父組件通過 this.setState 來修改父組件的值並渲染從而實現子向父傳值

bind(this,…args)

該方法主要是把當前實例綁定到方法目標方法中
如下面的代碼:
父組件

import React, { Component } from 'react';
import News from './New'
import Phone from './phone'
export default class componentName extends Component {
    constructor(props){
        super(props)
        this.state={
            text:"我是默認值"
        }
    }
    dataFun=(text)=>{
        this.setState({
            text
        })
    }
    render() {
        return (
            <div> 
                <News fufun={this.dataFun}/>
            </div>
        );
    }
}

子組件

import React, { Component } from 'react';
import PubSub from 'pubsub-js'
export default class componentName extends Component {
    constructor(props) {
        super(props)
        this.state = {
            ziText: "我是子組件的數據"
        }
    }
    render() {
        return (
            <div>
                <button onClick={this.props.fufun.bind(this,this.state.ziText)}>點我進行數據的發送</button>
            </div>
        );
    }
}
  1. 子組件的第一個參數this,表示將該方法的this指向自己(而不是父組件的this)
  2. 第二個參數就是上傳的值

兄弟間傳值

  1. npm i pubsub-js --save,該插件如同放置一個全局的map
  2. 導包 import PubSub from 'pubsub-js’
    兄弟1 組件
pubsub(){
      PubSub.publish('evt',this.state.num)
  }
<button onClick={this.pubsub.bind(this)}>點我進行同級傳值</button>

兄弟2組件
導包,然後就可以使用了

PubSub.subscribe("evt",(msg,data)=>{
    console.log("phone"+data)
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章