将数组作为属性发送到Typescript中的组件

2jcobegt  于 2022-11-18  发布在  TypeScript
关注(0)|答案(2)|浏览(111)

这应该很容易,但是我在类型管理中遇到了困难,试图将列表作为属性发送到组件。具体来说,我正在创建以下组件:

const [list, setList] = useState<Array<ToastProps>>([]);
...
<Toast toastlist={list}></Toast>

此组件设置为:

export interface ToastProps {
  id: number;
  title: string;
  description: string;
  backgroundColor: string;
}

export default function Toast(props: ToastProps[]) {
  return (
    <div>
      {props.map((toast, i) => (
        <div key={i} style={{ backgroundColor: toast.backgroundColor }}>
          <button>X</button>
          <div>
            <p>{toast.title}</p>
            <p>{toast.description}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

我有以下错误:
键入“{ toastlist:ToastProps[];}'无法指派给型别'IntrinsicAttributes & ToastProps[]'。
如何解决此问题?提前感谢您提供的任何帮助。

vdzxcuhz

vdzxcuhz1#

组件本身应该是这样。

export default function Toast({toastlist}: {toastlist:ToastProps[]}) {
 return (
    <div>
      {toastlist.map((toast, i) => (
        <div key={i} style={{ backgroundColor: toast.backgroundColor }}>
          <button>X</button>
          <div>
            <p>{toast.title}</p>
            <p>{toast.description}</p>
          </div>
        </div>
      ))}
    </div>
  );
}
ia2d9nvy

ia2d9nvy2#

编辑接口

export interface ToastList {
  id: number;
  title: string;
  description: string;
  backgroundColor: string;
}

export interface ToastProps {
  toastlist: ToastList[];
}

/////
const [list, setList] = useState<ToastList[]>([]);
...
<Toast toastlist={list}></Toast>
/////

export default function Toast(props: ToastProps) {
  return (
    <div>
      {props.map((toast, i) => (
        <div key={i} style={{ backgroundColor: toast.backgroundColor }}>
          <button>X</button>
          <div>
            <p>{toast.title}</p>
            <p>{toast.description}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

相关问题