简体   繁体   中英

Property 'theme' does not exist on type 'IntrinsicAttributes'.ts(2322)

I am a junior in TypeScript, I am trying to create a dark mode in TypeScript, using styled-components and a custom hook.

useDarkMode.tsx

import { useState } from 'react';

export const useDarkMode = () => {
  const [theme, setTheme] = useState('dark');

  const toggleTheme = () => {
    theme === 'dark' ? setTheme('light') : setTheme('dark');
  };

  return [theme, toggleTheme];
};

HeaderComponent.tsx

import styled from 'styled-components';
import { useDarkMode } from '../hooks';
import { ToggleTheme } from './';

const Header = styled.header`
  position: relative;
  width: 100%;
  display: inline-block;
  float: left;
  margin: 0;
  &:after {
    clear: both;
    content: '';
    display: table;
  }
`;

export const HeaderComponent = () => {
  const [theme, toggleTheme] = useDarkMode();
  console.log(theme);
  return (
    <>
      <Header>
                   // 👇️ ERROR HERE
        <ToggleTheme theme={theme} />
      </Header>
    </>
  );
};

下一张图片这里有错误

For some reason I get the following error:

(property) theme: any
Type '{ theme: any; toggleTheme: any; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'theme' does not exist on type 'IntrinsicAttributes'.ts(2322)

ToggleTheme.tsx

export const ToggleTheme = () => {
  return <div>ToggleTheme</div>;
};

The immediate cause of the error is that your <ToggleTheme> component has no such theme prop (nor toggleTheme ).

Here I guess you would like to use that <ToggleTheme> component as a button to trigger your toggleTheme function?

In that case, you would just attach that function to the onClick attribute:

<ToggleTheme onClick={() => toggleTheme()} />

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