我正在开发我的第一个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;
我希望按钮显示“现在玩”(expected output),但现在它保持空(actual output)。
此外,我找到了另一种解决方案,可以直接在每个按钮(MyButton的子项)中编写文本,并在需要时自定义它。
将“children”关键字作为“道具”传递给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>
如果您将所有道具传递给包裹的Button
,您将获得自定义Button
的最大灵活性。只要您在children
对象中使用与包装组件支持的classes
匹配的类键,这将自动处理styles
和CSS classes。
import React from "react";
import Button from "@material-ui/core/Button";
import { withStyles } from "@material-ui/core/styles";
const styles = () => ({
root: {
margin: 50,
padding: 10,
width: 180,
fontSize: 20,
fontWeight: "bold"
}
});
function CustomButton(props) {
return <Button variant="contained" color="primary" {...props} />;
}
export default withStyles(styles)(CustomButton);
请注意,在沙箱示例中,这允许您仍然利用Button
等其他disabled
功能,指定其他样式或覆盖CustomButton
中指定的某些属性。
如果您有一个需要明确处理children
的场景(在上面的示例中我使用了fontWeight
CSS而不是<b>
标记),您可以使用以下语法仍将所有道具传递给包装组件:
function CustomButton({children, ...other}) {
return <Button variant="contained" color="primary" {...other}><b>{children}</b></Button>;
}
将按钮文本作为道具传递给按钮组件
<MyButton text="Play now"></MyButton>
然后在MyButton组件中你可以得到它
function MyButton(props) {
const { classes,text } = props;
return (
<Button variant="contained" color="primary" className={classes.button}>
<b> {text} </b>
</Button>
);
}