父子组件通讯
- 父组件将方法传递给子组件,在 React 当中也会将父组件传递的,数据和函数信息直接存放在子组件当中,的 Props 属性对象当中
- React 的父子组件通讯的实现其实就是利用,函数的互相调用进行实现完成的
Header.js:
import React from 'react';
import './Header.css';
import ReactTypes from "prop-types";
class Header extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className={'header'}>我是头部</div>
<button onClick={() => {
this.btnClickFn()
}}>我是按钮
</button>
</div>
)
}
static defaultProps = {
name: '小灰灰',
age: 18
}
static propTypes = {
name: ReactTypes.string,
age: ReactTypes.number
}
btnClickFn() {
this.props.fatherFn('BNTang', 18);
}
}
export default Header;
App.js:
import React from 'react';
import './App.css';
import Footer from "./components/Footer";
import Main from "./components/Main";
import Header from "./components/Header";
class App extends React.Component {
render() {
return (
<div>
<Header name={'BNTang'} age={18} fatherFn={this.fatherFunction.bind(this)}/>
<Main/>
<Footer/>
</div>
)
}
fatherFunction(name, age) {
console.log(name, age);
}
}
export default App;