vue和react兩家對比之–組件之間的通信
文章目錄
Vue 組件通信
vue 中子組件獲取父組件的屬性
需要在組件標籤中 加入自定義屬性,然後再子組件中使用props接收這個傳過來的數據
如果傳過來的是一個父組件的方法則需要類似於上面的方法 使用@func=“func” 但是這個不需要使用props接收,子組件的方法中調用父組件的方法三,使用$emit() 第一個參數是名稱 第一個是傳入的參數數據,通過這種方法也可以把子組件中的數據傳入父組件中,有點類似於這個回調函數思想。
<body>
<div id="app">
<child-component v-bind:parentmsg="msg"></child-component>
<com2 @parent-click="parentClick"></com2>
</div>
<template id="children">
<div>
<h1>子組件{{childMsg}} ---- {{ parentmsg }}</h1>
</div>
</template>
<template id="com2">
<input @click="childClick" type="button" value="123456">
</template>
<script>
var com2 = {
template:"#com2",
methods:{
childClick() {
//調用父組件傳過來的方法
this.$emit('parent-click','123')
}
}
}
var vm = new Vue({
el: '#app',
data: {
msg:'父組件的內容'
},
methods: {
parentClick(data) {
console.log('123'+ data)
}
},
components: {
childComponent: {
template:"#children",
data() {
return {
childMsg:'123'
}
},
//接受這個父組件的屬性
props:['parentmsg']
},
//簡寫了 com2:com2
com2
}
})
</script>
</body>
vue中父組件獲取子組件的屬性
通過ref屬性,標籤中的ref屬性本來是作爲 獲取這dom節點,如果是對組件使用這個屬性,則可以獲取到這個組件對象,則就能獲取這個組件上的屬性。
body>
<div id="app">
<com1 ref="myInput" ></com1>
<input type="button" @click="handleClick" value="點擊">
</div>
<template id="temp">
<div>
<input type="text">
</div>
</template>
<script>
var com1 = {
template:'#temp',
data(){
return {
inputMsg:'123'
}
},
methods: {
show() {
console.log('123456')
}
}
}
var vm = new Vue({
el: '#app',
data: {
msg:''
},
methods:{
handleClick() {
//在父組件中調用
console.log(this.$refs.myInput)
}
},
components: {
com1
}
})
</script>
React 組件通信
react 中子組件獲取父組件的屬性
react中使用props是在組件中通信 ,也是使用再組件上定義屬性 向子組件傳遞信息例如:
render()
{
//Add中添加兩個屬性 一個count 一個addTodo 到 props中
const {todos} = this.state
return (
<div>
<h1>Simple TODO LIST</h1>
{//有兩個子組件分別是Add和List Add中傳入count 和 addTodo方法 List中傳入todos }
<Add count = {todos.length} addTodo ={this.addTodo}/>
<List todos = {todos}/>
</div>
)
}
Add組件 通過this.props.count 和this.props.addTodo()調用。
class Add extends React.Component{
constructor(props){
super(props)
this.add = this.add.bind(this)
}
add(){
const todo = this.todoInput.value.trim()
//內容爲空直接返回
if(!todo){
return
}
this.props.addTodo(todo)
//清空文本框中的內容
this.todoInput.value = ""
}
render()
{
// count = todos.length
// count 是從上面的父組件傳過來的
//ref 獲取標籤
return (
<div>
<input type="text" ref = {input => this.todoInput=input}/>
<button onClick = {this.add}>add #{this.props.count+1}</button>
</div>
)
}
}
//校驗
Add.propTypes = {
count :PropTypes.number.isRequired,
addTodo: PropTypes.func.isRequired
}
List組件在此處省略。。。。。
可以詳細參考這篇文章點擊進入
react中父組件調用子組件的屬性
這個同樣也是使用ref屬性 同樣這個屬性也是可以獲取dom節點的,跟vue類似 使用再組件上時可以獲取到這個組件對象,但是這個作用在組件上時需要再 Refs
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
當 ref 被傳遞給 render 中的元素時,對該節點的引用可以在 ref 的 current 屬性中被訪問。
const node = this.myRef.current
通過這樣我們可以訪問這個組件上的屬性,和操作這個組件。