- parent.jsx:
import React from "react";import ChildA from "./ChildA";import ChildB from "./ChildB";import ChildC from "./ChildC";import ChildD from "./ChildD";import ChildE from "./ChildE";import F from "./F";import './index.css'class Parent extends React.Component{state = {notice:'通知——今天有学生被开除了!',expelledNum:1,student:{name:'张三',age:21,reason:'逃课次数过多'},citys:['北京','上海','广州','深圳'],dogList:[{dogName:'麦兜',dogAge:3},{dogName:'贝塔',dogAge:2},]}getCityStrs =()=>{return this.state.citys;}addDog =(dog)=>{console.log('收到子组件添加的新dog:',dog);const dogList = this.state.dogList; const newDogList = [...dogList,dog]; console.log(newDogList);this.setState({dogList:newDogList});}render(){return(<div className="parent">我是父组件!<div className="childA"><ChildA notice={'通知——今天放假!'}/></div><div className="childB"><ChildB notice={this.state.notice} expelledNum={this.state.expelledNum} student={this.state.student}/></div><div className="childC"><ChildC getCityStrs={this.getCityStrs}/></div><div className="childD"><ChildD addDog={this.addDog}/></div><div className="childE"><ChildE dogList={this.state.dogList} testJsx={<p>测试一下传递jsx</p>}render={(kind)=><F petKind={kind}/>}/></div></div>)}}export default Parent;
- xxxA.jsx
import React from "react";class ChildA extends React.Component{render(){return(<div>我是子组件A!!!——类式组件<br /><br />收到来自于父组件的数据:{this.props.notice}</div>)}}export default ChildA;
- xxxB.jsx
function ChildB(props){const {name,age,reason} = props.student;return(<div>我是子组件B!!!——函数组件<br /><br />收到来自于父组件的数据:{props.notice}<br />被开除的人数是:{props.expelledNum}<br />被开除学生的信息:{name}-{age}-{reason}</div>)}export default ChildB;
- xxxC.jsx
function ChildC(props){const citys = props.getCityStrs();return(<div>我是子组件C!!!——函数组件<br /><br />收到父传子的函数,并调用函数获取了数据:{citys.map((city,index)=>{return <li key={index}>{city}</li>})}</div>)}export default ChildC;
- xxxD.jsx
function ChildD(props){const newDog = {dogName:'泡泡',dogAge:7};const addDog = props.addDog;return(<div>我是子组件D!!!——函数组件<br />{}<button onClick={()=>addDog(newDog)}>添加狗狗</button></div>)}export default ChildD;
- xxxE.jsx
function ChildE(props){console.log(props);const dogList = props.dogList;return(<div>我是子组件E!!!——函数组件<br />{props.testJsx}<br />展示狗狗信息:<ul>{dogList.map((dog,index)=><li key={index}>{dog.dogName}-{dog.dogAge}</li>)}</ul><hr />{}{}{props.render('狗狗')}</div>)}export default ChildE;
- F.jsx
function F(props){return(<div>我是E组件的子组件,我是F!!!——函数组件<br />接到E传来的宠物类型是:{props.petKind}</div>)}export default F;