- 基础组件(样式通过props传入的组件)
- 使用基础组件
- 用法
- 用法
- 使用基础组件
基础组件(样式通过props传入的组件)
使用基础组件
在React中使用组合的思想去构建我们的UI会带来很大的灵活性, 因为我们的组件从另一个角度来看都是函数.
通过改变组件中的props进而改变组件的样式, 我们能让组件更加的可复用.
我们把color和backgroundColor属性作为组件的props传入, 另外我们新加了一个props来调整padding top和padding bottom.
const Button = ({big,color = colors.white,backgroundColor = colors.blue,...props}) => {const sx = {fontFamily: 'inherit',fontSize: 'inherit',fontWeight: bold,textDecoration: 'none',display: 'inline-block',margin: 0,paddingTop: big ? space[2] : space[1],paddingBottom: big ? space[2] : space[1],paddingLeft: space[2],paddingRight: space[2],border: 0,color,backgroundColor,WebkitAppearance: 'none',MozAppearance: 'none'};return (<button {...props} style={sx}/>)};
用法
const Button = () => (<div><Button>Blue Button</Button><Button big backgroundColor={colors.red}>Big Red Button</Button></div>);// 通过Button组件的API去改变Button组件的样式,// 我们能得到样式各异的Button.const ButtonBig = (props) => <Button {...props} big/>;const ButtonGreen = (props) => <Button {...props} backgroundColor={colors.green}/>;const ButtonRed = (props) => <Button {...props} backgroundColor={colors.red}/>;const ButtonOutline = (props) => <Button {...props} outline/>;
