簡體   English   中英

react + typescript 如何修復道具類型錯誤

[英]react + typescript How to fix props type error

開發環境
・反應
・打字稿
・樣式化組件

問題
Open 是從父組件傳遞到下面的子組件。

<RightNav open={open}/>  

子組件①出現以下錯誤。 如果有懂的人請教教我

import React from 'react'
import styled from 'styled-components';

const Ul = styled.ul<{open: boolean}>`
  list-style: none;
  display: flex;
  flex-flow: row nowrap;

  li {
    padding: 18px 10px;
  }

  @media (max-width: 768px) {
    flex-flow: column nowrap;
    background-color: #0D2538;
    position: fixed;
    transform: ${({ open }) => open ? 'translateX(0)' : 'translateX()100%'};
    top: 0;
    right: 0;
    height: 100vh;
    width: 300px;
    padding-top: 3.5rem;

    li {
      color: #fff;
    }
  }
`
const RightNav = () => {
  return (
   // ① Ul in error
    <Ul>
      <li>Home</li>
      <li>About Us</li>
      <li>Contact Us</li>
      <li>Sign Up</li>
      <li>Sign In</li>
    </Ul>
  )
}

export default RightNav

  ①  [ts] Property 'open' is missing in type '{ children: Element[]; }' but required in type 'Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement>, "slot" | "style" | "title" | "key" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | ... 247 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }, "slot" | ... 255 more ... | "open"> & Partial<...>, "sl...'. [2741]
    RightNav.tsx(4, 23): 'open' is declared here.

您需要接受組件的 open 屬性,然后將其傳遞給樣式化組件

const RightNav = ({open}) => {
  return (
    <Ul open={open}>

如果您注意到...樣式化組件的類型定義需要open屬性

const Ul = styled.ul<{open: boolean}>`
-----------------------^-------------

並且父級使用 open 屬性渲染這個組件

<RightNav open={open}/>
-----------^---------

所以你只需要在你的組件中接受那個道具,然后傳遞給Ul樣式的組件:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM