ReactHook——组件之间的传值

父组件传递子组件

父组件传递子组件——数据

引入子组件

import Marqueecom from "./components/marquee";

使用子组件

      <Header></Header>
        <Marqueecom></Marqueecom>
      <Footer></Footer>

定义一个数据 进行传递

const marqueedata = [
  {
    text: 11111,
  },
  {
    text: 22222,
  },
];
//完整的使用
<Marqueecom data={marqueedata}></Marqueecom>

完整父组件的代码

import React, { useEffect, useState, useContext, createContext } from "react";
import Header from "../../components/header/index";
import Footer from "../../components/footer/index";
import Marqueecom from "./components/marquee";

const marqueedata = [
  {
    text: 11111,
  },
  {
    text: 22222,
  },
];
const Home = () => {
  const [marqueelist,setmarqueelist]:any = useState([])
  useEffect(()=>{
    setmarqueelist(marqueedata)
  },[])
  return (
    <>
      <Header></Header>
        <Marqueecom data={marqueedata}></Marqueecom>
      <Footer></Footer>
    </>
  );
};
export default Home;

子组件

在props中拿到该值 进行操作

const Marqueecom = (props: { data: any; }) => {
    const {data}= props
  return(
    <>
    <Marquee pauseOnHover={true} speed={60} loop={0} gradient={false}>
      {data.map((item:any) => (
        <span className="red">{item.text}</span>
      ))}
    </Marquee>
  </>
  )
};

父组件传递子组件方法——子组件调用父组件方法

父组件

  const [sisters,setsisters]=useState('村里一朵花')
  <Changefather sisters={sisters} setsisters={setsisters}></Changefather>

完整代码

import React, { useEffect, useState, useContext, createContext } from "react";
import Changefather from './components/changefather'
const Home = () => {
  const [sisters,setsisters]=useState('村里一朵花')
  return (
    <>
        <Changefather sisters={sisters} setsisters={setsisters}></Changefather>
    </>
  );
};
export default Home;

子组件

 const {sisters,setsisters} = props;
<button onClick={()=>setsisters('老太婆')}>时间的变迁</button>

完整代码

import React, { useEffect, useState, useContext, createContext } from "react";
interface sister{
    sisters:string,
    setsisters:any
}
const Changeyears = (props:sister)=>{
    const {sisters,setsisters} = props;
    return (
        <>
        <div>
            {sisters}
        </div>
        <button onClick={()=>setsisters('老太婆')}>时间的变迁</button>
        </>
    )
}
export default Changeyears

子组件传递给父组件

父组件获取子组件——数据

父组件代码

  const [childData,setChildData]:any = useState();//获取子组件的值
    const getchildfn  = useCallback((data:any)=>{
    setChildData(data)
  },[])
  																// ↓↓↓↓↓↓
    <Changefather sisters={sisters} setsisters={setsisters} handleChildData={getchildfn} ></Changefather>
  //渲染一下子组件传给父组件的值
          {
          <div>
            这是子组件的值{childData}
          </div>
        }

父组件完整代码

import { useCallback, useEffect, useState } from "react";
import Header from "../../components/header/index";
import Footer from "../../components/footer/index";
import Changefather from "./components/changefather";

const Home = () => {
  const [sisters, setsisters] = useState("村里一朵花");
  const [loding, setloding] = useState(false); //loding;
  const [childData,setChildData]:any = useState();//获取子组件的值
  const changeloding = () => {
    setloding(true);
    setTimeout(() => {
      setloding(false);
    }, 1000);
  };
  const getchildfn  = useCallback((data:any)=>{
    setChildData(data)
  },[])
  return (
    <div className="home">
      <div className="home_div">
        <Header headeractive={1}></Header>
        <Changefather sisters={sisters} setsisters={setsisters} handleChildData={getchildfn} ></Changefather>
        <div className="buttondiv">
          <span>这是一个小小的button</span>
          <div className="lodingdiv" style={loding ? {} : { display: "none" }}>
            <div className="loding"></div>
          </div>
        </div>
        <button
          onClick={() => {
            changeloding();
          }}
        >
          changeloding
        </button>
        {
          <div>
            这是子组件的值{childData}
          </div>
        }
        <input type="number" placeholder="555" />
      </div>
      <Footer></Footer>
    </div>
  );
};
export default Home;

子组件代码

  const { sisters, setsisters,handleChildData } = props;
  const [childtext , setchildtext ] = useState('')
  useEffect(()=>{
    handleChildData(childtext)
  },[childtext])
  //两个按钮进行改变
        <div onClick={()=>{
        setchildtext('今天给爸爸洗脚')
      }}>传给父组件值</div>
      <div onClick={()=>{
        setchildtext('今天不给爸爸洗脚')
      }}> 第二次传给父组件的值</div>

子组件完整代码

import{ useEffect, useState } from "react";
import Countdown from "react-countdown";
import dayjs from "dayjs";

interface sister {
  sisters: string;
  setsisters: any;
  handleChildData:any;
}
const Changeyears = (props: sister) => {
  const { sisters, setsisters,handleChildData } = props;
  const [Cdtime,setCdtime]=useState(dayjs(1649999957832).valueOf())
  const [childtext , setchildtext ] = useState('')
  useEffect(()=>{
    handleChildData(childtext)
  },[childtext])
  return (
    <>
      <Countdown date={Cdtime} 
       renderer={time => {
         const {days,hours,minutes,seconds} = time.formatted
         return (
           <div>
             还有{days}{hours}{minutes}{seconds}</div>
         )
       }}
      />
      <div onClick={()=>{
        setchildtext('今天给爸爸洗脚')
      }}>传给父组件值</div>
      <div onClick={()=>{
        setchildtext('今天不给爸爸洗脚')
      }}> 第二次传给父组件的值</div>
      <div className="animate__flash">{sisters}</div>
      <button onClick={() => setsisters("老太婆")}>时间的变迁</button>
    </>
  );
};
export default Changeyears;

父组件调用子组件——方法

父组件

  const childMethodRef:any = useRef();
    const handleChildFun = () => {
    childMethodRef.current.fun2()
  };
        <div
        onClick={() => {
          handleChildFun();
        }}
      >
        我要
      </div>

子组件

  const { sisters, setsisters,handleChildData,cRef } = props;
  useImperativeHandle(cRef, () => ({
    childFun (info: any) {
    console.log(info)
    },
    fun2(){
    console.log('fun2')
    }
    }));

父组件完整代码

import { useCallback, useEffect, useState, useRef } from "react";
import Header from "../../components/header/index";
import Footer from "../../components/footer/index";
import Changefather from "./components/changefather";

const Home = () => {
  const [sisters, setsisters] = useState("村里一朵花");
  const [loding, setloding] = useState(false); //loding;
  const [childData, setChildData]: any = useState(); //获取子组件的值
  const childMethodRef:any = useRef();
  const changeloding = () => {
    setloding(true);
    setTimeout(() => {
      setloding(false);
    }, 1000);
  };
  const handleChildFun = () => {
    childMethodRef.current.fun2()
  };
  const getchildfn = useCallback((data: any) => {
    setChildData(data);
  }, []);
  return (
    <div className="home">
      <div className="home_div">
        <Header headeractive={1}></Header>
        <Changefather
          sisters={sisters}
          setsisters={setsisters}
          handleChildData={getchildfn}
          cRef={childMethodRef}
        ></Changefather>
        <div className="buttondiv">
          <span>这是一个小小的button</span>
          <div className="lodingdiv" style={loding ? {} : { display: "none" }}>
            <div className="loding"></div>
          </div>
        </div>
        <button
          onClick={() => {
            changeloding();
          }}
        >
          changeloding
        </button>
        {<div>这是子组件的值{childData}</div>}
        <input type="number" placeholder="555" />
      </div>
      <div
        onClick={() => {
          handleChildFun();
        }}
      >
        我要
      </div>
      <Footer></Footer>
    </div>
  );
};
export default Home;

子组件完整代码

import{ useEffect, useState ,useImperativeHandle,forwardRef} from "react";
import Countdown from "react-countdown";
import dayjs from "dayjs";

interface sister {
  sisters: string;
  setsisters: any;
  handleChildData:any;
  cRef:any
}
let Changeyears = (props: sister):any => {
  const { sisters, setsisters,handleChildData,cRef } = props;
  const [Cdtime,setCdtime]=useState(dayjs(1649999957832).valueOf())
  const [childtext , setchildtext ] = useState('')
  useImperativeHandle(cRef, () => ({
    childFun (info: any) {
    console.log(info)
    },
    fun2(){
    console.log('fun2')
    }
    }));
  useEffect(()=>{
    handleChildData(childtext)
  },[childtext])
  return (
    <>
      <Countdown date={Cdtime} 
       renderer={time => {
         const {days,hours,minutes,seconds} = time.formatted
         return (
           <div>
             还有{days}{hours}{minutes}{seconds}</div>
         )
       }}
      />
      <div onClick={()=>{
        setchildtext('今天给爸爸洗脚')
      }}>传给父组件值</div>
      <div onClick={()=>{
        setchildtext('今天不给爸爸洗脚')
      }}> 第二次传给父组件的值</div>
      <div className="animate__flash">{sisters}</div>
      <button onClick={() => setsisters("老太婆")}>时间的变迁</button>
    </>
  );
};

Changeyears = forwardRef(Changeyears);

export default Changeyears;

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值