【问题标题】:Typescript not allowing to pass props to children with React-notification-component {children?: ReactNode;}打字稿不允许使用 React-notification-component {children?: ReactNode;} 将道具传递给孩子
【发布时间】:2021-06-07 08:02:45
【问题描述】:

我正在使用 lib React-notifications-components 创建自定义通知。我需要将 id 从内容道具传递给子组件(通知),以便使用 onClick 事件关闭通知。但是当尝试这样做时,TypeScript 不断报告我: “类型 '{ children?: ReactNode;} 上不存在属性 'id'”

---------父亲-------

import { store } from 'react-notifications-component';

  const notification = () => {
    store.addNotification({
      id: 'myId',
      content: p => (
        <Notifications
          handleCloseConfirm={() => store.removeNotification(p.id)}
        />
      ),
      width: 500,
      container: 'bottom-left', // where to position the notifications
      animationIn: ['animated', 'fadeIn'], // animate.css classes that's applied
      animationOut: ['animated', 'fadeOut'], // animate.css classes that's applied
      dismiss: {
        duration: 0,
        // pauseOnHover: true,
        click: false,
        touch: false,
      },
    });
  };

-----------child component----------

import React from 'react';
import { Container, Wrapper } from './styles';
import { Icon } from '../../commons';

interface NotificationsProps {
  handleCloseConfirm: () => void;
}

const Notifications: React.FC<NotificationsProps> = props => {
  const { handleCloseConfirm } = props;

  const handleSubmit = () => {
    handleCloseConfirm();
  };

  return (
    <Container>
      <div>
        <Icon iconName="notifications_success" />
      </div>
      <Wrapper>
        <p>Registro alterado com sucesso</p>
        <Icon iconName="notifications_close" onClick={() => handleSubmit} />
      </Wrapper>
    </Container>
  );
};

export default Notifications;



【问题讨论】:

  • 似乎问题出在内容回调接收到的 p 变量的类型上。可能 addNotification 是一个通用函数?我必须查看这个包的文档。

标签: reactjs typescript children react-notifications-component


【解决方案1】:

我查看了文档,似乎 Typescript 类型有错误。

content 被定义为不带任何道具的组件:

content?: React.ComponentClass | React.FunctionComponent | React.ReactNode;

但是docs 说它将接收id 作为道具:

自定义通知内容,必须是 Class Component、Functional Component 或 React 元素。如果作为函数或类组件提供,id 将作为 prop 提供


您可以使用p as any 绕过该错误。

handleCloseConfirm={() => store.removeNotification((p as any).id)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-17
    • 2016-03-19
    • 1970-01-01
    • 2020-09-15
    • 2018-07-29
    • 2020-08-08
    • 2023-03-18
    • 2021-11-10
    相关资源
    最近更新 更多