reactjs - 如何在 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;
解决方案
此外,我还找到了另一种解决方案,可以直接在每个按钮(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>
推荐阅读
- python - 使用共享轴创建一个 2x2 的 python seaborn 热图网格
- javascript - React - 调用子级时在父级中调用 setState
- c# - 为什么兔子出奇的慢?
- java - 在 Akka Actor 的静态上下文中使用记录器
- javascript - Webpack 多文件入口包
- python - 通过c(debian)在终端中运行python模块
- java - 使用 java 程序从一个子模块的 Maven 安装阶段到另一个子模块
- sqlite - 离子 Sqlite 不在 chrome 上运行
- java - Kafka Streams:商店尚未准备好
- r - 使用 r-script 将 JSON 从 NodeJS 传递到 R