React父子组件传值

父组件给子组件传值

思路:把需要传递的值获取,并放入state中,并把state中的值通过props传递给子组件;子组件在根据父组件传递来的值进行处理。

// 首先创建父组件
class ParentCom extends React.Component{
  constructor(props){
    super(props)
    this.state=({
      content:'给子传input',
      zi_content:''	// 这个是需要传递的值
    })
  }
  // 父组件通过此方法,把需要传递的值,放入state中。
  giveValue = (e) =>{
    let value = document.getElementById("fu_input").value;
    this.setState({
      zi_content : value
    });
  }
  render(){
    return(
      <div>
        <Button onClick={this.giveValue}>给子传值</Button>
        <Input id="fu_input" defaultValue={this.state.content}></Input>
        {/* 把需要传递的值,传递给子组件 */}
        <ChildCom zi_content = {this.state.zi_content}/>
      </div>
    )
  }
}
// 创建子组件
class ChildCom extends React.Component{
  constructor(props){
    super(props)
  }
  render(){
    let val = '';
    if(this.props.zi_content){
    	// 获取props中,父组件传递过来的值
      val = this.props.zi_content
    }
    return(
      <div>
        <div>我是子</div>
        <Input defaultValue={val} value={val}></Input>
      </div>
    )
  }
}
ReactDOM.render(
  <ParentCom />,
  document.getElementById('root')
)

子组件给父组件传值

思路:由于子组件并不能直接处理父组件的状态,但是我们可以通过父组件的方法更改父组件的状态。

// 创建父组件
class FuCom extends React.Component{
  constructor(props){
    super(props)
    this.state=({
      zi_value:"" 
    })
  }
  // 父组件定义方法 可以修改父组件的值,把这个方法传递给子组件
  changeData = (msg,e) =>{
    this.setState({
      zi_value:msg
    })
  }
  render(){
    return(
      <div>
        子组件传来的值:
        <span>{this.state.zi_value}</span>
        {/*把修改父组件数据的函数传递给子组件*/}
        <ZiCom changeData={this.changeData}/>
      </div>
    )
  }
}
// 创建子组件
class ZiCom extends React.Component{
  constructor(props){
    super(props)
    this.state=({
      input_val:"子组件的初始内容"
    })
  }
  // 子组件接收 从父组件传来的 修改父组件值的方法 传递参数 修改父组件的值
  sendData = (e) =>{
    let val = document.getElementById("inputId").value;
    this.props.changeData(val)
  }
  render(){
    return(
      <div>
        <Input type="text" id="inputId" defaultValue={this.state.input_val} ></Input>
        <Button onClick={this.sendData}>给父传值</Button>  
        <Button onClick={(e)=>{this.props.changeData('Hello world',e)}}>直接通过props 函数</Button>
        {/* <Button onClick={function(e){this.changeData('dd',e)}.bind(this)}>不使用es6绑定函数</Button> */}
      </div>
    )
  }
}

ReactDOM.render(
  <FuCom />,
  document.querySelector('#root2')
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值