49
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React / Next】親から関数をpropsで子へ渡したら「is not assignable to type ts(2322)」の型エラーがでた

Last updated at Posted at 2022-04-22

親コンポーネントで定義した関数を子コンポーネントへ渡す時に、型エラーが出たのでその解決方法の議事録です。

環境

  • next: 11.1.3
  • react: 17.0.2

やろうとしたこと

  • 親コンポーネント側で、子コンポーネントのボタンがクリックされた時の関数を定義
  • 関数を子コンポーネントへpropsで渡す
export const Parent = () => {
	const handleClick() {
		//
	}

	return (
		<Children handleClick={handleClick} />
	)
}
interface Props {
	handleClick: Function;
}

export const Children = (props: Props) => {
	return (
		<Button onClick={props.handleClick}>Click</Button>
	)
}

エラーメッセージ

(property) onClick?: MouseEventHandler<HTMLButtonElement> | undefined
Type 'Function' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.

Type 'Function' provides no match for the signature '(event: MouseEvent<HTMLButtonElement, MouseEvent>): void'.ts(2322)
index.d.ts(1451, 9): The expected type comes from property 'onClick' which is declared here on type 'IntrinsicAttributes & Children'

解決方法

  • onClick={() => handleClick} のように関数でラップする
  • 引数ありでもこれでOK
interface Props {
	handleClick: Function;
}

export const Children = (props: Props) => {
	return (
		<Button onClick={() => props.handleClick}>Click</Button>
	)
}

関数の引数があるパターン

export const Parent = () => {
	const handleClick(id: UUID) {
		//
	}

	return (
		<Children handleClick={handleClick} />
	)
}
interface Props {
  handleClick: Function;
}

export const Children = (props: Props) => {
  return (
    <>
      {users.map((user) => {
        <Button onClick={() => props.handleClick(user.id)}>Click</Button>;
      })}
    </>
  );
};

型をきっちり記述するパターン

export const Parent = () => {
	const handleClick(id: UUID) {
		//
	}

	return (
		<Children handleClick={handleClick} />
	)
}
interface Props {
  handleClick: (_id: UUID) => void;
}

export const Children = (props: Props) => {
  return (
    <>
      {users.map((user) => {
        <Button onClick={() => props.handleClick(user.id)}>Click</Button>;
      })}
    </>
  );
};

文献

49
52
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?