🔖

React Propsの渡し方

2024/12/02に公開

propsが親コンポから直接に渡すケース

送り側

function Props() {
  const [num, setNum] = useState((_) => 0);
  const [msg, setMsg] = useState("hello");

  const handleChange1 = (e) => {
    setMsg(e.target.value);
  };

  return (
    <Fragment>
      <div className="Props">
        <div>
          the number is {num} and the message is {msg}
        </div>
        <button onClick={() => setNum(num + 1)}>add</button>
        <input value={msg} onChange={handleChange1}></input>
      </div>

      {/* 渡す */}
      <ComA num={num} msg={msg} />
    </Fragment>
  );
}

export default Props;

受け側の書き方

function ComA(props) {
  function doSomethingWithProps() {
    // もらったプロパティを取得して何かする
    console.log(props.msg);
    console.log(props.num);
    console.log(JSON.stringify(props));
  }

  return (
    <Fragment>
      <div>comA --- {props.msg}</div>
      <div>comA --- {props.num}</div>
      <button onClick={doSomethingWithProps}> print Props </button>
      {/* <div>comA --- {JSON.stringify(props)}</div> */}
    </Fragment>
  );
}

export default ComA;

コンポをプロパティとして渡す

受け側 (共通Layoutとして役に立ちそう?)

type Props = {
  goodsName: string;
  count: number;
  amount: number;
};

//  type PropsWithChildren<Props> = Props & { children?: React.ReactNode | undefined };
const CommonCartLayout: FC<PropsWithChildren<Props>> = ({ children }) => {
  return <div style={{ background: "cyan" }}> {children} </div>;
};

export default CommonCartLayout;

又は

type MyProps = {
  goodsName: string;
  count: number;
  amount: number; 
  children?:  React.ReactNode; // children属性名は変更不可
};

const CommonCartLayout: FC<MyProps> = ({ goodsName, children }: MyProps) => {
  // const CommonCartLayout: FC<PropsWithChildren> = ({ children }) => {
  return (
    <Fragment>
      <p>{goodsName}</p>
      <div style={{ background: "cyan" }}>{children}</div>
    </Fragment>
  );
};

export default CommonCartLayout;

プロパティ名はchildrenの時の渡し方 オススメ

<CommonCartLayout>
  <div>this is the children node</div>
</CommonCartLayout>

(プロパティ名はchildren以外の時の渡し方 ex. childNode)

<CommonCartLayout childNode={<div>this is the children node</div>}>
  {/* <div>this is the children node</div> */}
</CommonCartLayout>

ちなみにFCとは

type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
  (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
  propTypes?: WeakValidationMap<P>;
  contextTypes?: ValidationMap<any>;
  defaultProps?: Partial<P>;
  displayName?: string;
}

参照

Discussion