1.父组件向子组件传值// 父组件import React from "react";import Child from "./Child";export default class Parent extends React.Component { constructor(props) { super(props); this.state = { title: "父传子的标题", } } render() { return <Child title={this.state.title} /> }} // 子组件import React from "react";export default class Child extends React.Component { constructor(props) { super(props); } render() { return <h1>{this.props.title}</h1> }} 2.子组件调用父组件的方法// 父组件import React from "react";import Child from "./Child";export default class Parent extends React.Component { constructor(props) { super(props); } render() { return <Child getInfo={this.getInfo} /> } getInfo = () => { console.log("这是父组件的方法"); }} // 子组件import React from "react";export default class Child extends React.Component { constructor(props) { super(props); } render() { return <button onClick={this.props.getInfo}>子调父方法</button> }} 3.子组件向父组件传值(通过回调的形式,从子组件向父组件传值) // 父组件import React from "react";import Child from "./Child";export default class Parent extends React.Component { constructor(props) { super(props); } render() { return <Child getChildInfo={this.getInfo} /> } getInfo = (info) => { console.log(info); //输出子组件里的值 }} // 子组件import React from "react";export default class Child extends React.Component { constructor(props) { super(props); } return ( <button onClick={()=>{this.props.getChildInfo("这是子的值")}}> 子向父传值 </button> )} 4.父组件调用子组件的方法// 父组件import React from "react";import Child from "./Child";export default class Parent extends React.Component { constructor(props) { super(props); } render() { return ( <div> <Child onRef={(ref) => this.Child = ref } /> <button onClick={this.click}>父调子的方法</button> </div> ) } click = () => { this.Child.getChild(); // 调用子的方法 }} // 子组件import React from "react";export default class Child extends React.Component { constructor(props) { super(props); } componentDidMount() { this.props.onRef(this); } render() { return <h1>test</h1> } getChild = () => { console.log("父调子成功!"); }} ← Previous Post Next Post → 1.父组件向子组件传值2.子组件调用父组件的方法3.子组件向父组件传值4.父组件调用子组件的方法