函数组件
// 复用按钮组件
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 形式)
class Button extends Component {
// 定义默认 props(对应函数组件的默认参数)
static defaultProps = {
type: "default"
};
render() {
// 从 this.props 中解构参数
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 形式)
class Parent extends Component {
render() {
return (
<div>
<Button text="提交" type="primary" onClick={() => {}} />
<Button text="取消" onClick={() => {}} />
</div>
);
}
}
// 导出父组件供使用
export default Parent;