在开发过程中,经常会遇到父组件和子组件之间相互通信,React子组件和父组件通信包括以下几个方面:
1,子组件调用父组件的方法
(1)子组件要拿到父组件的属性,需要通过 this.props
方法。
(2)同样地,如果子组件想要调用父组件的方法,只需父组件把要被调用的方法以属性的方式放在子组件上,
子组件内部便可以通过“this.props.被调用的方法
”这样的方式来获取父组件传过来的方法。
2,父组件调用子组件的方法
在 ReactJS 中有个叫 ref 的属性。这个属性就像给组件起个引用名字一样,子组件被设置为 ref 之后(比如 ref=“xxx”)。父组件便可以通过 this.refs.xxx
来获取到子组件了。
多级的传递
- 如果还存在孙子组件的情况呢?如下图,黑框为父,绿框为子,红框为孙,要求子孙的数据都传给爷爷。原理一样的,只是父要将爷爷对孙子的处理函数直接传下去。
-
-
父类调用子类的函数和属性
- 通过refs获取
- 如下为Parent.jsx ,Child.jsx,Grandson.jsx 多级传递,ButtonComment.jsx与Parent.jsx实现互相调用。
- Parent.jsx
-
import React, { Component } from 'react';
import Child from './Child';
import ButtonComment from './ButtonComment';
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
username: 'zw',
sex: 'nan',
sendCount: 100
}
}
getSwordCount = () => {
this.setState({sendCount:this.refs.getSwordButton.state.count + 1});
}
handleSelect = (event) => {
this.setState({
sex: event.target.value
});
}
handleVal = (event) => {
this.setState({
username: event.target.value
});
}
sendSword = () => {
console.log(this.refs);
this.refs.getSwordButton.sendSword();
}
render() {
return (
<div>
<div>用户姓名:{this.state.username}</div>
<div>用户性别:{this.state.sex}</div>
<Child handleVal={this.handleVal} handleSelect={this.handleSelect}/>
<ButtonComment ref="getSwordButton" getSwordCount={this.getSwordCount} buttonName="儿子送宝刀"/>
<button onClick={this.sendSword}>通过老爸送宝刀</button>
<p>
父子俩共送{this.state.sendCount}把宝刀!!!
</p>
</div>
);
}
}
export default Parent;
-
Child.jsx
-
import React, { Component } from 'react';
import Grandson from './Grandson';
import PropTypes from 'prop-types';
class Child extends Component {
static propTypes = {
handleVal: PropTypes.func,
handleSelect: PropTypes.func,
}
render() {
return (
<div>
姓名:<input onChange={this.props.handleVal}/>
<Grandson handleSelect={this.props.handleSelect}/>
</div>
);
}
}
export default Child;
-
Grandson.jsx
-
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Grandson extends Component {
static propTypes = {
handleSelect: PropTypes.func,
}
render() {
return (
<div>性别:
<select onChange={this.props.handleSelect}>
<option value="男">男</option>
<option value="女">女</option>
</select>
</div>
);
}
}
export default Grandson;
-
ButtonComment.jsx
-
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class ButtonComment extends Component {
static propTypes = {
buttonName: PropTypes.string,
getSwordCount: PropTypes.func,
}
constructor(props) {
super(props);
this.state = {
count: 100
}
}
sendSword = () => {
// var newCount = this.state.count + 1;
this.setState({
count: this.state.count + 1
});
this.props.getSwordCount();
}
render() {
return (
<div>
{/* <button onClick={this.sendSword}>{this.props.buttonName}</button> */}
</div>
);
}
}
export default ButtonComment;
-
文档摘自:https://blog.csdn.net/qq_30638831/article/details/88855932
-
代码自己集成实现。