父子组件通讯
- 父组件将方法传递给子组件,在 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('yangbuyiya', 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={'yangbuyiya'} age={18} fatherFn={this.fatherFunction.bind(this)}/> <Main/> <Footer/> </div> ) } fatherFunction(name, age) { console.log(name, age); } } export default App;
最后
本期结束咱们下次再见👋~
🌊 关注我不迷路,如果本篇文章对你有所帮助,或者你有什么疑问,欢迎在评论区留言,我一般看到都会回复的。大家点赞支持一下哟~ 💗