父组件
import React, { Component } from 'react';
import Head from "../components/Head"
class Comp extends Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
}
run = () => {
console.log("我的来自父组件的方法")
}
childVal = (value) => {
// 获取子组件传递的值
this.setState({
value: value
})
}
getChild = (child) => {
// 获取整个子组件的实例
// 也可以通过使用ref获取
console.log(child)
}
render() {
return (
<div>
{/* parent={this}可将整个父组件的值和方法传递给子组件 */}
<Head title="明知山" func={this.run} parent={this} getChild={this.getChild}></Head>
{this.state.value}
</div>
);
}
}
export default Comp;
子组件
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Head extends Component {
constructor(props) {
super(props);
this.state = {
msg: "我是子组件"
};
}
componentDidMount() {
// 通过this.props接受父组件的值和方法
this.props.func()
console.log(this.props.parent) //获取整个父组件实例
// 子组件给父组件的方法传递参数
this.props.parent.childVal("子组件给父组件传递参数")
this.props.getChild(this)
}
render() {
return (
<div>接收父组件传递的值:{this.props.title}</div>
);
}
}
// 如果父组件没有传入title值,赋默认值
Head.defaultProps = {
title: "标题"
}
// 通过PropTypes来验证传入的title为string类型
Head.propTypes = {
title: PropTypes.string
};
export default Head;