函数组件
function Button({ text, onClick, type = "default" }) {
const styles = {
primary: { backgroundColor: "blue", color: "white" },
default: { backgroundColor: "gray" }
};
return (
<button style={styles[type]} onClick={onClick}>
{text}
</button>
);
}
function Parent() {
return (
<div>
<Button text="提交" type="primary" onClick={() => {}} />
<Button text="取消" onClick={() => {}} />
</div>
);
}
export default Parent;
类组件
import React, { Component } from 'react';
class Button extends Component {
static defaultProps = {
type: "default"
};
render() {
const { text, onClick, type } = this.props;
const styles = {
primary: { backgroundColor: "blue", color: "white" },
default: { backgroundColor: "gray" }
};
return (
<button style={styles[type]} onClick={onClick}>
{text}
</button>
);
}
}
class Parent extends Component {
render() {
return (
<div>
<Button text="提交" type="primary" onClick={() => {}} />
<Button text="取消" onClick={() => {}} />
</div>
);
}
}
export default Parent;