组件之间的通讯是面试中极为常见的问题,也是在实际工做中会常常遇到的问题,因此今天来总结一下关于组件通讯方面的知识点。vue
注: 虽然能够经过ref来获取子组件的实例或DOM,可是在实际项目中,并不推荐这样作。React和Vue优化的本质就是经过操做虚拟DOM,来避免操做真实DOM,提升性能。而使用ref违背了这样的初衷。react
子组件中:
this.$emit('hello', 'helloWorld');
父组件中:
<child @hello="sayHello" />
复制代码
// 父组件
<Child hello={this.hello} />
// 子组件
static propsTypes = {
hello: Proptypes.func
}
render() {
return {
<button onClick={this.props.hello}>hello</button>
}
}
复制代码
// 兄弟组件1
this.$parent.$on('hello',handle);
// 兄弟组件2
this.$parent.$emit('hello')
复制代码
// 父组件
<A setValue={this.setValue}/>
<B value={this.state.value} /> 复制代码
// 祖先组件
provide() {
return {hello: 'hello'}
}
// 后代组件
inject: ['hello']
复制代码
// React.createContext 建立Context对象的API
const StatusContext = React.createContext({
disabled: false
});
// 祖先组件
<StatusContext.Provider value={{disabled: true}}>
<Children />
</StatusContext.Provider>
// 后代组件
<StatusContext.Consumer>
{context => (
<button disabled={context.disabled}>
hello
</button>
)}
</StatusContext.Consumer>
复制代码
注:面试
对于后代向祖先之间的通讯,其实vue和react采用的方法本质上是同样的,都是子组件一级一级向上通知。不一样vue的实现相比于react的要简单的多。vuex
// 后代组件
function dispatch(eventName, data){
let parent = this.$parent
while (parent) {
parent.$emit(eventName,data)
parent = parent.$parent
}
}
<button @click="dispatch('hello', 'hello,world')">
{{ msg }}
</button>
// 祖先组件
this.$on('hello', this.sayHello)
复制代码
// main.js
Vue.prototype.$bus = new Bus()
// 组件A
this.$bus.$on('hello', handle)
// 组件B
this.$bus.$emit('hello')
复制代码
事件总线的方式虽然能够实现任意组件中的通讯,可是在实际开发中,使用的很是少。由于当项目较大时,可能会涉及到不少组件中的通讯,使用$bus,会让你的代码很是杂乱。redux
以上就是React和Vue中常见的组件通讯,若是有错误的地方,但愿各位大神多多指正。bash