简体   繁体   中英

spread props in react using typescript

When I first started to adapt typescript in react, I notice I can't using ...props , as typescript check every single prop that are passed in the components. It's great but it's also annoying, where I have to pass native props like id, name etc declaratively as props.


interface MyComponentProps {
  name: string,
  id: string,
  placeholder: string
}

const MyComponent = ({
  name,
  id,
  placeholder
}: MyComponentProps) => {
  return <input type="text" placeholder={placeholder} name={name} id={id}/>
}
export default function App() {
  return (
    <div className="App">
      <MyComponent placeholder="Name" name="something" id="myInput" />
    </div>
  );
}

You should edit your interface such that it is extending the props of the HTML input element:

interface MyComponentProps extends InputHTMLAttributes< HTMLInputElement>)  {
  // add other custom props
}

const MyComponent: React.FC<MyComponentProps> = (props) => (...)

You can explicitly cast it to HTMLAttributes

Declare an interface like union of component's props with HTMLAttributes

interface MyComponentProps = {}

const MyComponent: React.FC<MyComponentProps & HTMLAttributes>...

Detailed explanation you can find here: https://stackoverflow.com/a/40032869/4186110

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM