React,Material-UI:如何使用打字稿用定制的道具组成功能组件 [英] React, Material-UI: How to composition functional component with customized props using typescript

查看:93
本文介绍了React,Material-UI:如何使用打字稿用定制的道具组成功能组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Material-ui中的Button使MyCustomButton合成

I'm trying to make MyCustomButton compositioning with Button in Material-ui

import React from "react";
import { Button, ButtonProps } from "@material-ui/core";

interface MyButtonProps {
  'aria-label': string, // I'd like to add a aria-label as required property
  myOptionalProperty?: string
}

export default function MyButton(buttonProps: ButtonProps, myButtonProps: MyButtonProps) {
  return (
    <Button {...buttonProps, ...myButtonProps} />
  );
}

并且我收到以下错误代码: 解析错误:需要表达.

And I've got an error code following: Parsing error: expression expected.

我已经通过 material-ui中的官方文档来获得一些信息,但是我还没做完.

I've get some information via official documents in material-ui, but I haven't done composition.

完整代码位于 https://codesandbox.io/s/jolly-dawn-keuj5

有人给我一些解决方案吗?

Does anyone give me some solution?

谢谢您的时间.

推荐答案

猜测您不需要将两个道具传递给<Button />

Guessing you don't need to pass two props to <Button />

import React from "react";
import { Button, ButtonProps } from "@material-ui/core";

interface MyButtonProps {
  title: string,
  myOptionalProperty?: string
}

export default function MyButton<P extends ButtonProps>(myButtonProps: MyButtonProps) {
  return (
    <Button {...myButtonProps as P} />
  );
}


在线尝试:


Try it online:

如果这与您的需求不符,或者错过了重要事项,请通知我

Info me if this doesn't fit your demand or I missed something important

这篇关于React,Material-UI:如何使用打字稿用定制的道具组成功能组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆