react传值

文章目录

  • 父子传值
    • 父组件
    • 子组件
  • 状态管理

父子传值

父组件

import { useState } from "react";
import Zi from "./Zi";

const Comp: React.FC = () => {
  const initialCount = 0;
  const [parentCount, setParentCount] = useState<number>(0);
  const getChildCount = (val: number) => {
    setParentCount(val);
  };
  return (
    <>
      <p>父组件当前值:{parentCount}</p>
      <Zi initialCount={initialCount} getCount={getChildCount} />
      {/* 
         setParentCount(val)}
        /> 
      */}
    </>
  );
};
export default Comp;

子组件

import { useState } from "react";

type selfProps = {
  initialCount: number;
  getCount: Function;
};
const Comp: React.FC<selfProps> = ({ initialCount, getCount }) => {
  const [count, setCount] = useState<number>(initialCount);
  const addCount = () => {
    setCount(count + 1);
    getCount(count + 1);
  };
  return (
    <>
      <hr />
      <p>子组件从父组件获取的初始值:{initialCount}</p>
      <p>子组件当前值:{count}</p>
      <button onClick={() => addCount()}>递增</button>
    </>
  );
};
export default Comp;

状态管理

见前期笔记
umi

你可能感兴趣的:(react.js,javascript,前端)