react实现 fullname
实现 FullName 组件的几种方法
在 React 中实现 FullName 组件可以通过多种方式完成,以下是几种常见的实现方法:
方法一:使用函数组件
function FullName({ firstName, lastName }) {
return (
<div>
{firstName} {lastName}
</div>
);
}
// 使用示例
<FullName firstName="John" lastName="Doe" />
方法二:使用类组件

class FullName extends React.Component {
render() {
const { firstName, lastName } = this.props;
return (
<div>
{firstName} {lastName}
</div>
);
}
}
// 使用示例
<FullName firstName="Jane" lastName="Smith" />
方法三:带有默认值的函数组件
function FullName({ firstName = '', lastName = '' }) {
return (
<div>
{firstName} {lastName}
</div>
);
}
// 使用示例
<FullName firstName="Alice" />
方法四:使用 TypeScript 的类型检查

interface FullNameProps {
firstName: string;
lastName: string;
}
const FullName: React.FC<FullNameProps> = ({ firstName, lastName }) => {
return (
<div>
{firstName} {lastName}
</div>
);
};
// 使用示例
<FullName firstName="Bob" lastName="Johnson" />
方法五:带有样式和类名的增强版
function FullName({ firstName, lastName, className }) {
return (
<div className={`full-name ${className}`}>
<span className="first-name">{firstName}</span>
<span className="last-name">{lastName}</span>
</div>
);
}
// 使用示例
<FullName
firstName="Emily"
lastName="Davis"
className="user-name"
/>
方法六:使用 React Hooks 管理状态
function FullName() {
const [firstName, setFirstName] = React.useState('');
const [lastName, setLastName] = React.useState('');
return (
<div>
<input
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
placeholder="First Name"
/>
<input
value={lastName}
onChange={(e) => setLastName(e.target.value)}
placeholder="Last Name"
/>
<div>
Full Name: {firstName} {lastName}
</div>
</div>
);
}
这些方法展示了不同场景下实现 FullName 组件的方案,可以根据具体需求选择合适的实现方式。简单的展示组件可以使用前几种方法,需要交互功能的可以使用最后一种方法。






