js 实现component
JavaScript 实现 Component
在 JavaScript 中实现组件化开发有多种方式,可以根据具体需求选择不同的方法。以下是几种常见的实现方式:
使用 ES6 Class 实现组件
通过 ES6 的类语法可以创建可复用的组件类:

class Component {
constructor(props) {
this.props = props || {};
this.state = {};
}
setState(newState) {
this.state = { ...this.state, ...newState };
this.render();
}
render() {
throw new Error('render() must be implemented');
}
}
class MyComponent extends Component {
render() {
return `<div>${this.props.text}</div>`;
}
}
使用函数式组件
函数式组件是更简单的实现方式,适合无状态的 UI 组件:
function Button(props) {
return `<button class="${props.className}">${props.label}</button>`;
}
const button = Button({ className: 'primary', label: 'Click me' });
使用 Web Components
原生 Web Components 提供了标准的组件化方案:

class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
:host { display: block; }
</style>
<div>Custom Element</div>
`;
}
}
customElements.define('my-element', MyElement);
使用工厂函数模式
工厂函数可以创建具有私有状态的组件:
function createCounter() {
let count = 0;
return {
increment() {
count++;
},
getCount() {
return count;
},
render() {
return `<div>Count: ${count}</div>`;
}
};
}
const counter = createCounter();
使用模块模式
结合闭包和立即执行函数可以创建隔离的组件:
const Component = (function() {
const privateMethod = () => {
console.log('Private method');
};
return {
publicMethod() {
privateMethod();
return 'Public method';
}
};
})();
每种实现方式都有其适用场景,ES6 Class 适合复杂的组件逻辑,函数式组件适合简单 UI,Web Components 适合需要原生支持的情况,工厂函数和模块模式适合需要封装私有状态的情况。






