返回
父组件获取子组件数据及调用子组件方法的套路
前端
2023-10-04 00:40:16
前言
现在每天写的最多的就是组件了,必不可少地会碰到处理组件之间数据传递的问题。涉及到父子组件通信的话一般分为子组件获取父组件的数据以及方法和父组件获取子组件的数据以及方法。这篇文章就是总结React、Vue父组件如何伸手获取子组件的数据以及调用子组件方法的。
React
父组件获取子组件数据
在React中,父组件可以通过props
获取子组件的数据。props
是一个特殊的对象,它包含了父组件传递给子组件的数据。子组件可以通过this.props
访问props
对象。
// 父组件
class ParentComponent extends React.Component {
render() {
return (
<ChildComponent name="John" age={30} />
);
}
}
// 子组件
class ChildComponent extends React.Component {
render() {
return (
<div>
<h1>{this.props.name}</h1>
<p>{this.props.age}</p>
</div>
);
}
}
父组件调用子组件方法
在React中,父组件可以通过ref
获取子组件的实例。通过子组件的实例,父组件就可以调用子组件的方法。
// 父组件
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
render() {
return (
<div>
<ChildComponent ref={this.childRef} />
<button onClick={() => this.childRef.current.sayHello()}>Say Hello</button>
</div>
);
}
}
// 子组件
class ChildComponent extends React.Component {
sayHello() {
console.log("Hello!");
}
render() {
return (
<div>
<h1>{this.props.name}</h1>
<p>{this.props.age}</p>
</div>
);
}
}
Vue
父组件获取子组件数据
在Vue中,父组件可以通过props
获取子组件的数据。props
是一个特殊的对象,它包含了父组件传递给子组件的数据。子组件可以通过this.$props
访问props
对象。
// 父组件
<template>
<ChildComponent name="John" age={30} />
</template>
<script>
export default {
components: {
ChildComponent
}
}
</script>
// 子组件
<template>
<div>
<h1>{{ this.$props.name }}</h1>
<p>{{ this.$props.age }}</p>
</div>
</template>
<script>
export default {
props: ['name', 'age']
}
</script>
父组件调用子组件方法
在Vue中,父组件可以通过$refs
获取子组件的实例。通过子组件的实例,父组件就可以调用子组件的方法。
// 父组件
<template>
<ChildComponent ref="child" />
<button @click="child.sayHello()">Say Hello</button>
</template>
<script>
export default {
components: {
ChildComponent
},
methods: {
sayHello() {
this.$refs.child.sayHello()
}
}
}
</script>
// 子组件
<template>
<div>
<h1>{{ this.name }}</h1>
<p>{{ this.age }}</p>
</div>
</template>
<script>
export default {
props: ['name', 'age'],
methods: {
sayHello() {
console.log("Hello!")
}
}
}
</script>
总结
以上就是父组件获取子组件数据以及调用子组件方法的套路。希望对你有帮助。