components---》child.js
import React from "react"; class Child extends React.Component{ state ={ childname:'子组件名字:qq', childage:'子组件年纪:20', childmsg:"这是来自子类的消息" } change = () => { this.props.callback(this.state.childmsg,this.state.childname,this.state.childage); } render(){ return( <div id='a'> <div> {this.props.childname}</div> <div>{this.props.childage}</div> <button onClick={this.change}>点击</button> </div> ) } } export default Child;
parent.js
import React from "react"; import Child from './child' class Parent extends React.Component{ constructor(props) { super(props); this.state={ msg:'这是父组件的消息', name:'父组件名字:蔡蔡', age:'父组件年龄:25' } } callbackAAA =(childmsg,childname,childage) => { this.setState({ msg:childmsg, name:childname, age:childage }); } render(){ return( <div id='xxx'> <p> Message: {this.state.msg}</p> <Child callback={this.callbackAAA} childage={this.state.age} childname={this.state.name} ></Child> </div> ); } } export default Parent;
index.js
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import Parent from './components/parents'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Parent/> </React.StrictMode> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();