Tìm kiếm trang web

reactjs - Làm thế nào để gõ props mới trong React.cloneElement?


Tôi thích truyền một hàm cập nhật trạng thái xuống tất cả các phần tử con như thế này:

React.Children.toArray(children)
.map(child => React.isValidElement(child) ?
React.cloneElement(child, {setNewItemPopup : setNewItemPopup}) : child)

TS nói với tôi:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ setNewItemPopup: React.Dispatch<React.SetStateAction<NewItemPopupProps | null>>; }' is not assignable to parameter of type 'Partial<unknown> & Attributes'.
      Object literal may only specify known properties, and 'setNewItemPopup' does not exist in type 'Partial<unknown> & Attributes'.ts(2769)

Tôi không biết làm thế nào để gõ trong trường hợp này. Có ai đó có thể giúp tôi không?

Câu trả lời #1

Vì isValidElement nhận một P tổng quát là props và trả về một ReactElement<P> hợp lệ, nên miễn là bạn đặt props cho nó là props của phần tử mà bạn sao chép, thì nó sẽ hoạt động.

Tóm lại, thiết lập như sau:

// Just replace `any` with your actual type
// while `{ setNewItemPopup: any }` is the props of `child`
React.isValidElement<{ setNewItemPopup: any }>(child);

// so full code looks like this:
React.Children.toArray(children).map((child) =>
    React.isValidElement<{ setNewItemPopup: any }>(child) ? React.cloneElement(child, { setNewItemPopup: setNewItemPopup }) : child
  );

Bài viết liên quan