我正在开发我的第一个 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 组件的另一个组件:主页:
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;
我希望按钮显示“立即播放”( expected output ),但现在它仍然是空的 ( actual output )。
最佳答案
此外,我还找到了另一种解决方案,可以直接在每个按钮(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>
关于reactjs - 如何在 react-app 中重用自定义 Material-ui 按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935001/