【问题标题】:TypeScript React, unable to send props to componentTypeScript React,无法向组件发送道具
【发布时间】:2021-04-21 07:11:06
【问题描述】:

我有一个简单的按钮组件,我使用样式化组件对其进行样式设置,但我无法向组件发送简单的道具,因为 TypeScript 抱怨 No overload matches this call

App.tsx

import React from 'react';

import Button from '../form/button';

export const App = (): React.ReactElement => <Button secondary>Click me</Button>;

Button.tsx

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

const StyledButton = styled.button`
  background-color: #333;
  padding: 10px 20px;
  color: ${({ secondary }) => (secondary ? 'white' : 'red')};
`;

interface Props {
  children: string;
  secondary?: any;
}

const Button: React.FC<Props> = ({ children, secondary }) => (
  <StyledButton secondary={secondary}>{children}</StyledButton>
);

export default Button;

这应该可以,TypeScript 需要我指定什么?该错误不是很有帮助

【问题讨论】:

标签: reactjs typescript styled-components


【解决方案1】:

因为你没有把props传给styled组件,所以它不知道secondary是什么。

你可以像这样传递你的道具(我删除了children,因为你不需要手动指定)

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

interface Props {
  secondary?: any;
}

const StyledButton = styled.button<Props>`
  background-color: #333;
  padding: 10px 20px;
  color: ${({ secondary }) => (secondary ? "white" : "red")};
`;


const Button: React.FC<Props> = ({ children, secondary }) => (
  <StyledButton secondary={secondary}>{children}</StyledButton>
);

export default Button;

代码沙盒:https://codesandbox.io/s/determined-worker-62xtm?file=/src/form/Button.tsx

【讨论】:

  • 谢谢,事实证明我仍然需要将辅助类型更改为布尔值才能正常工作,但是有了这个,你的更改现在就很好了
  • 是的,boolean 是您应该使用的。 ;)
【解决方案2】:

您可以指定传递然后解构的道具来自接口Props并访问参数secondary

const StyledButton = styled.button`
  background-color: #333;
  padding: 10px 20px;
  color: ${({secondary}: Props) => (secondary ? 'white' : 'red')}
`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2020-01-22
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多