父传子props传值

方法一 普通传值

import React , {Component} from 'react'

calss Father extends Component{
  render(){

    return(
      <div>
      // 通过title传值
          <One title="我是父组件传的值"/>
      </div>
    )
  }
}

// 子组件
import React , {Component} from 'react'

calss Son extends Component{
  render(){
    // 子组件接收位置
    rteurn(

    <div>
    //链式使用
    <h1>{this.props.title}</h1>
    </div>
    )
  }
}

方法2 传入对象

import React , {Component} from 'react'

calss Father extends Component{
  render(){
    // 在这里声明变量
const obj={
  name:'我是Two',
  age:18,
}
const obj2 = {
      a: 'aaaa',
      b: 'bbbbb',
      c:'ccccc',
    }

    return(
      <div>
    //  可以传一个对象 也可以解构的对象一起传给子级 
           <Two data={obj} {...obj2} />
      </div>
    )
  }
}

// 子组件
import React , {Component} from 'react'

calss Son extends Component{
  render(){
    // 子组件接收位置
    const {name,age} = this.props.data //接收data 方式1
    const {data} = this.props // 接收data 方式2
    const {a,b,c} = this.pops//接收解构的对象{...obj2}
    rteurn(

    <div>
    // 调用方式
    <h1>{this.props.data.name}</h1>
    <h2>{data.a}<h2>
    <h3>{a}</h3>
    <h4>{b}</h4>
    </div>
    )
  }
}

方法3 传入模块

import React , {Component} from 'react'

calss Father extends Component{
  render(){

    return(
      <div>
      // 闭合标签表示有传入内容 会被注入一个children 
        <Three>
          <a href='true'> &lt;&lt; 更多</a>
        </Three>
        // 单标签表示无内容 不会传入children
        <Three/>
      </div>
    )
  }
}

// 子组件
import React , {Component} from 'react'

calss Son extends Component{
  render(){
    // 子组件接收位置
    rteurn(
      <div>
      // 如果父级为空,不显示 父级有内容自动获取父级内容
          {this.props.children}
      </div>
      
    )
  }
}

方法四 传入组件

import React , {Component} from 'react'

calss Father extends Component{
  render(){

    return(
      <div>
      // 给组件中传入令一个组件
        <Four five={ <Five/> }/>
        <Four six={ <Six/> }/>
      </div>
    )
  }
}

// 子组件
import React , {Component} from 'react'

calss Son extends Component{
  render(){
  
    rteurn(
      <div>
      // 子组件直接接受组件
          {this.props.five}
          {this.props.six}
      </div>
    )
  }
}

p71a3fj5
1 声望0 粉丝