js实现组件
JavaScript 组件实现方法
使用原生 JavaScript 创建组件
通过创建自定义类或函数来封装组件逻辑和模板。
class ButtonComponent {
constructor(text) {
this.text = text;
}
render() {
const button = document.createElement('button');
button.textContent = this.text;
button.addEventListener('click', () => {
console.log('Button clicked');
});
return button;
}
}
// 使用组件
const myButton = new ButtonComponent('Click me');
document.body.appendChild(myButton.render());
使用 Web Components 标准
利用 Custom Elements 和 Shadow DOM 创建可重用的封装组件。
class MyComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
padding: 10px;
border: 1px solid #ccc;
}
</style>
<div>Custom Component Content</div>
`;
}
}
// 注册组件
customElements.define('my-component', MyComponent);
使用 React 创建组件
通过 React 的函数组件或类组件模式实现。
// 函数组件
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
// 类组件
class Counter extends React.Component {
state = { count: 0 };
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
使用 Vue 创建组件
通过 Vue 的单文件组件或选项式 API 实现。

<template>
<div>
<p>{{ message }}</p>
<button @click="changeMessage">Change Message</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
};
},
methods: {
changeMessage() {
this.message = 'Message changed!';
}
}
};
</script>
组件通信方式
- Props/Attributes: 父组件向子组件传递数据
- Events/Callbacks: 子组件向父组件发送消息
- State Management: 使用 Redux/Vuex 等状态管理库
- Context/Provide/Inject: 跨层级组件通信
组件生命周期管理
- Mounting: 组件创建和插入 DOM
- Updating: 组件重新渲染
- Unmounting: 组件从 DOM 移除
- Error Handling: 捕获子组件错误
组件性能优化
- Memoization: 缓存计算结果
- Virtualization: 长列表优化
- Lazy Loading: 动态导入组件
- Pure Components: 减少不必要的渲染
组件测试策略
- Unit Testing: 测试独立功能
- Integration Testing: 测试组件交互
- E2E Testing: 测试完整用户流程
- Snapshot Testing: 验证 UI 一致性






