首页 > 解决方案 > 如何在 react-app 中重用自定义 Material-ui 按钮?

问题描述

我正在开发我的第一个 React 应用程序。我已经导入了 Material-ui 按钮并对其进行了自定义。

现在我想在我的应用程序的几个组件中重用这个自定义按钮。每次使用此自定义按钮时,我都希望使用不同的文本。

我需要在哪里为每个按钮编写此特定文本?

我的按钮在其他组件中导入时可见,但看不到我在按钮组件中编写的文本。该按钮保持为空。

我的自定义按钮组件:MyButton:

import React from "react";
import Button from "@material-ui/core/Button";
import { withStyles } from "@material-ui/core/styles";

const styles = () => ({
  button: {
    margin: 50,
    padding: 10,
    width: 180,
    fontSize: 20
  }
});

function MyButton(props) {
  const { classes } = props;
  return (
    <Button variant="contained" color="primary" className={classes.button}>
      <b>  </b>
    </Button>
  );
}

export default withStyles(styles)(MyButton);

我导入 MyButton 组件的另一个组件: Home :

import React from "react";
import "../App.css";
import MyButton from "./Button";

function Header() {
  return (
    <header className="Header">
      {/* background image in css file */}
      <h1>Welcome </h1>
      <h3> description...</h3>
      <MyButton>Play now</MyButton>
    </header>
  );
}

export default Header;

我希望按钮显示“立即播放”(预期输出),但现在它保持为空(实际输出)。

标签: reactjsbuttoncomponentsmaterial-uireusability

解决方案


此外,我还找到了另一种解决方案,可以直接在每个按钮(MyButton 的子按钮)内编写文本,并在需要时对其进行自定义。

将“children”关键字作为“props”传递给 MyButton 组件:

function MyButton(props) {
  const { classes, children } = props;
  return (
    <Button variant="contained" color="primary" className={classes.button}>
      <b>{children}</b>
    </Button>
  );
}

然后像在 html 中一样在按钮内写入按钮的文本:

<MyButton> Play now </MyButton>

推荐阅读