我试图使用风格的组件样式我自己的孩子组成。
举个例子,我创建了一个自定义的卡组件,名为myCard,如下所示:
import React from "react";
import Card, { CardActions, CardContent } from "material-ui/Card";
import Button from "material-ui/Button";
import Typography from "material-ui/Typography";
const myCard = props => {
return (
<Card>
<CardContent>
<Typography>{props.cardName}</Typography>
</CardContent>
<CardActions>
<Button size="small">SELECT</Button>
</CardActions>
</Card>
);
};
export default myCard;
现在,在父组件,我想重用此myCard组分,而是给他们中的任何一个自定义样式,如边框(当我最终重构代码的onClick)的可能性:
import React, { Component } from "react";
import Grid from "material-ui/Grid";
import styled from "styled-components";
import myCard from "./myCard";
const StyledCard = styled(myCard)`
/* border-style: ${props => (props.border ? "solid" : "none")}; */
border-style: solid !important;
border-width: 5px;
width: 180px;
`;
class cardSelect extends Component {
render() {
return (
<div>
<Grid container spacing={24}>
<Grid item xs={12}>
<Grid container justify="center">
<Grid item>
<StyledCard
cardName="Bronze"
/>
</Grid>
<Grid item>
<StyledCard
cardName="Silver"
/>
</Grid>
<Grid item>
<StyledCard
cardName="Gold"
/>
</Grid>
</Grid>
</Grid>
</Grid>
</div>
);
}
}
export default cardSelect;
我承认,我觉得风格组件文件比较差。而只有一个参考这种情况,这表明在类名道具传递给该组件。但是我没有真正理解这个概念。
通过与符号道具,你{...props}
卡组件。
import React from "react";
import Card, { CardActions, CardContent } from "material-ui/Card";
import Button from "material-ui/Button";
import Typography from "material-ui/Typography";
const myCard = props => {
return (
/**Here, pass the props with spread notation */
<Card {...props}>
<CardContent>
<Typography>{props.cardName}</Typography>
</CardContent>
<CardActions>
<Button size="small">SELECT</Button>
</CardActions>
</Card>
);
};
export default myCard;
因此,实际上,当你通过任何道具组件请问这个蔓延的道具做这将成为该组件的一部分。
所以,你真的需要通过className
支撑到Card
组件。该风格的组件生成类的你,申请样式not-styled-components
只需要道具的className传递到组件...
const myCard = props => {
return (
<Card className={props.className}>
<CardContent>
<Typography>{props.cardName}</Typography>
</CardContent>
<CardActions>
<Button size="small">SELECT</Button>
</CardActions>
</Card>
);
};
我发现,通过试验和错误的答案。找不到该解决方案(至少整体)的任何地方,因此为子孙后代和其他人的利益,这是我如何解决它。
该解决方案是简单地在支柱的className传递给myCard组分如下:
const myCard = props => {
const { className } = props;
return (
<Card className={className}>
...
因此,在一般情况下,一个有转嫁的className道具要呈现的自定义组件。