React组件间信息传递方式

父传子

父组件定义一个 name get

constructor(props) {
        super(props)
        this.state = {
            name: "小明",
            get:1
        }
		render() {
		        return (
		            <div>
		                爷爷
		                <Fuqin listname="name" listget= "get"/>
		            </div>
		        );
		    }
    }

子组件通过 this.props 接收

 render() {
        console.log(this.props)
        let {listname , listget} = this.props
        return (
            <div>
             {listname}
             {listget}
            </div>
        )
    }

子传父

先在父组件定义一个方法

class app1 extends Component {
    constructor(props) {
        super(props)
         this.state = {
            title: '' "
        }
        this.fn = this.fn.bind(this) // 如果里面有值就在这绑定一下 this
 }
    fn(q){
        console.log(q)
      this.setState ({
          title :'我是老大'
      })
      
    }
    render() {
      	  let { fn } = this
        // console.log(fn)
        
        return (
            <div>
            我是父亲
            {this.state.title}
            //冲这里发送一个收子组件接收
            <Div div = {this.state.title} fn = {fn}/>
            </div>
        )
    }
}

在子组件定义一个事件 接收 父组件的方法

class app2 extends Component {
    constructor(props) {
        super(props)
    }
  //fn(){
  //	 let {fn} = this.props
  //	 fn()
  //}
  //这种方法多次一举
   render() {
   			let {fn} = this.props
        return (
            <div>
             <button onClick = {() => {fn("我是儿子传过去的")}}>我是儿子</button>
            </div>
        )
    }
}

跨组件传

先下载

npm install prop-types -S 

在爷爷组件

import PropTypes from 'prop-types'
class Index extends Component {
    constructor(props) {
        super(props)
    }
    // 第一步:父组件提供一个函数,用来返回相应的context的对象
    getChildContext() {
        return {
            name: '熊大',
            like: '睡觉'
        }
    }
    render() {
        let { username, like } = this.props
        return (
            <div>
                我是爷爷组件
                <List listUserName={ username } listLike={ like } />
            </div>
        )
    }
}

// 第二步:父组件声明自己支持的context,并提供context中属性的校验
yeye.childContextTypes = {
    name: PropTypes.string,
    like: PropTypes.string
}

儿子组件

import PropTypes from 'prop-types'
class erzi extends Component {
    constructor(props) {
        super(props)
    }
    render() {
        console.log(this.context)
        let { name, get } = this.context
        return (
            <div>
                儿子组件
                {name}
                {get}
            </div>
        );
    }
}
// 第三步: 跨组件需要声明自己需要使用的context,并校验
erzi.contextTypes = {
    name : PropTypes.string,
    get:PropTypes.string
}

猜你喜欢

转载自blog.csdn.net/qq_35506117/article/details/82827517