React子组件与父组件之间的通信

1. 父组件向子组件通信
,子组件通过**this.props.*****与父组件通信,

//父组件,将时间传递给子组件
import React,{Component} from 'react';
import Children from './App';

class Parent extends Component{
   constructor(props){
       super(props);
       this.state={
           date : `${new Date().getHours()}:
                   ${new Date().getMinutes()}:
                   ${new Date().getSeconds()}`
       }
   }
   render(){
        return(
            <div>
                <Children date = {this.state.date}/>
            </div>  
    )
   }
}

export default Parent;
//子组件
import React,{Component} from 'react';

class  Children extends Component{
 constructor(props){
   super(props)
 }
 render(){
   return(
     <div>
       <span>{this.props.date}</span>
     </div>
   ) 
 }
}

export default  Children;

2.子组件向父组件通信
子组件向父组件通信一般用回调函数,父组件事先定义好回调函数。并将回调函数传递给子组件,子组件调用回调函数,向父组件通信。

//父组件
import React,{Component} from 'react';
import Children from './App';

class Parent extends Component{
    constructor(props){
        super(props);
        this.state={
            index : 0
        }
    }
    getNumCallback = (num) => {
        this.setState({
            index :num
        })
        alert(this.state.index)
    }
    render(){
            return(
                <div>
                    <Children 
                        date = {this.state.date} 
                        getNumCallback = {this.getNumCallback.bind(this)}
                        />  
                </div>  
        )
    }
}
export default Parent;
//子组件
import React,{Component} from 'react';

class  Children extends Component{
  constructor(props){
    super(props);
    this.state = {
      num : 0
    }
  }
 
  numClickHander = ()=>{
    this.props.getNumCallback(this.state.num+1)
    this.setState({
      num:this.state.num +1
    })
  }

  render(){
    return(
      <div>
        <button onClick = {this.numClickHander.bind(this)}>{this.state.num}</button>
      </div>
    ) 
  }
}
export default  Children;
### Vue 3 父组件的使用方法 在 Vue 3 中,父组件可以通过 `props` 向子组件传递数据,并通过监听自定义事件来接收来自子组件的消息。此外,父组件还可以利用 `$refs` 来直接访问子组件实例并调用其方法。 以下是关于如何实现这些功能的具体说明和示例: #### 1. **父组件子组件传递数据** 父组件可以使用 `v-bind` 或者简写形式 (`:`) 将数据作为属性绑定到子组件上。这种通信方式被称为“父传子”。 ```html <template> <div> <!-- 使用 v-bind (或 :) 将 data 属性传递给子组件 --> <ChildComponent :message="parentMessage" /> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentMessage: '这是来自父组件的信息', }; }, }; </script> ``` 子组件需要声明它接受哪些 `props`: ```javascript // ChildComponent.vue export default { props: ['message'], // 声明 message 是一个 prop template: `<p>{{ message }}</p>`, }; ``` 上述代码展示了父组件如何将消息传递给子组件[^3]。 --- #### 2. **父组件监听子组件发出的事件** 当子组件触发某个操作时(比如点击按钮),它可以使用 `$emit` 方法通知父组件父组件则可以在模板中监听该事件。 **子组件发送事件:** ```html <!-- ChildComponent.vue --> <button @click="sendEventToParent">通知父组件</button> <script> export default { methods: { sendEventToParent() { this.$emit('custom-event', '这是子组件发来的消息'); }, }, }; </script> ``` **父组件监听事件:** ```html <template> <div> <ChildComponent @custom-event="handleCustomEvent" /> <p>接收到的消息:{{ receivedMessage }}</p> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { receivedMessage: '', }; }, methods: { handleCustomEvent(message) { this.receivedMessage = message; }, }, }; </script> ``` 此部分描述了父组件如何响应子组件的事件[^1]。 --- #### 3. **父组件调用子组件的方法** 如果需要让父组件主动调用子组件中的某些方法,则可以借助 `ref` 实现这一目标。 **子组件暴露方法:** ```html <!-- ChildComponent.vue --> <script> export default { methods: { childMethod() { console.log('子组件方法被调用了!'); }, }, }; </script> ``` **父组件通过 ref 调用子组件方法:** ```html <template> <div> <ChildComponent ref="childRef" /> <button @click="callChildMethod">调用子组件方法</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { callChildMethod() { this.$refs.childRef.childMethod(); // 调用子组件方法 }, }, }; </script> ``` 这里介绍了父组件如何通过引用名调用子组件内部的方法[^2]。 --- #### 总结 以上三种方式分别涵盖了父组件子组件传输数据、监听子组件事件以及直接调用子组件方法的核心场景。每种技术都有其适用范围,在实际开发过程中可以根据需求灵活选用。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值