React父子組件傳參
首先要了解React中定義組件的兩種方式:
函數(shù)式組件
與 class組件
,如有不了解的可以看React之組件介紹及用法詳解
接下來實(shí)現(xiàn)父子組件傳參使用class組件(父子組件傳參為一套代碼石咬,以下有分析)
//父組件
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
name: "我是父組件的name"
}
}
render() {
return (
<div className="test-list">
<h1>我是父組件</h1>
<Child handleParent={this.handleClick.bind(this)} name={this.state.name} />
</div>
);
}
/**子組件傳入父組件的方法 */
handleClick(val) {
console.log(val, 'val')
}
}
//子組件
import React, { Component } from 'react';
class child extends Component {
constructor(props) {
super(props)
this.state = {
message: "我是子組件的message",
color: 'blue'
}
}
render() {
return (
<div>
<h2 onClick={this.handleClick.bind(this)}>我是child子組件{this.state.color} · {this.props.name}</h2>
</div>
);
}
/**子組件傳父組件 */
handleClick() {
this.props.handleParent(this.state)
}
}
export default child;
分析:
1.先看看父傳子
了解過vue的小伙伴會發(fā)現(xiàn)谍婉,除了語法上不一樣陶因,用法如出一轍森枪,通過v-bind:parent="parent"傳入子組件誉简,然后子組件通過props屬性取到parent柄沮。再回過頭看react回梧,在父組件引入的子組件上定義 name={this.state.name}废岂,子組件取值不像vue那么麻煩,先定義屬性再取值狱意,而是直接取值this.props.name 湖苞,這個(gè)this.props后面的name就是父組件中=前面定義的name
2.子傳父
在vue中子傳父,通過this.$emit 方法實(shí)現(xiàn)详囤,this.$emit("方法名",傳入的參數(shù))财骨,在父組件中引入的子組件上添加子組件傳入的方法名即可,如:<child @方法名="handleClick">藏姐。在react中亦是如此隆箩,都是傳一個(gè)方法到子組件。
先在子組件中的方法中定義 this.props.handleParent(傳到父組件的值)包各,然后再父組件中引入的子組件上添加子組件傳入的方法摘仅,如:
<Child handleParent={this.handleClick.bind(this)} name={this.state.name} />
總結(jié):在不考慮底層的情況下,兩個(gè)框架的父子組件傳參方式都類似问畅,個(gè)人認(rèn)為單從寫法上vue依賴自身的屬性方法娃属,在react上則是直接定義直接取,相比較之下护姆,vue多套了一層矾端。