React中组件的传值方式

1.父组件给子组件传值

import React from 'react'
import ReactDOM from 'react-dom'
class Holle extends React.Component{
     
    constructor(){
     
        super()
        this.state={
     
            msg:'这是子组件的私有数据'
        }
    }
    //使用class创建的组件,不需要用props作为参数接收传值,直接使用this.props就可以获取传值
	//!!这里this.props获取的值也是只能读的
    render(){
     
      this.state.msg=this.props.msg
    return  <h1>Holle {
     this.state.msg}</h1>
    }
}
class HolleFather extends React.Component{
     
    constructor(){
     
        super()
        this.state={
     
            msg:'这是父组件的私有数据'
        }
    }
    render(){
     
        return (
            <div>
                <Holle msg={
     this.state.msg}></Holle>
            </div>
        )
    }
}
ReactDOM.render(
<div>
   <HolleFather></HolleFather>
    
</div>
,document.getElementById('app'))

2.父组件获取子组件中的值

  1. 父组件通过向子组件传递一个方法,来获取子组件中的值
import React from 'react'
import ReactDOM from 'react-dom'
class Holle extends React.Component{
     
    constructor(){
     
        super()
        this.state={
     
            msg:'这是子组件的私有数据'
        }
    }
    render(){
     
    return (
        <div>
        <button onClick={
     this.setFatherMsg}>向父元素传递数据</button>
        </div>) 
    }
    //这里必须使用箭头函数
    setFatherMsg=()=>{
     
       this.props.setMsg(this.state.msg)
       
    }
}
class HolleFather extends React.Component{
     
    constructor(){
     
        super()
        this.state={
     
            msg:'这是父组件的私有数据'
        }
    }
    render(){
     
        return (
            <div>
                <Holle  setMsg={
     this.setMsg}></Holle>
                <p>这是父元素中的数据:{
     this.state.msg}</p>
            </div>
        )
    }
    //这里必须使用箭头函数
    setMsg=(childMsg)=>{
     
        console.log(childMsg)
        this.setState({
     msg:childMsg})
    }
}

这两处要使用箭头函数,是将该方法的this绑定到组件实例的this中,这样才能访问到this.state。
箭头函数详情参考箭头函数
也可以将这里的箭头函数写入到,标签中,但注意有传参时必须传参,例如

 <Holle  setMsg={
     (a)=>this.setMsg(a)}></Holle>

总结
本质上都是通过向子组件的props对象传递数据或方法,实现组件间的数据传递
父组件向子组件的props传递数据或方法的方式,是直接在使用子组件的标签时,向标签加一个键值对(属性名=值),这里的值可以是父组件中的任意对象
在子组件向父组件传值中,是通过父组件向子组件的props传递一个方法,让子组件调用这个方法,将子组件的数据传递给父组件的方法进行处理
在父组件想子组件传值中,是通过父组件向子组件的props传递一个数据,子组件可以直接通过props直接获取这个数据

你可能感兴趣的:(react,js)