js 实现component
实现组件的基本方法
在JavaScript中实现组件通常涉及创建可复用的代码块,这些代码块可以封装特定的功能或UI元素。以下是几种常见的实现方式:
使用类(Class)实现组件
class ButtonComponent {
constructor(text) {
this.text = text;
}
render() {
const button = document.createElement('button');
button.textContent = this.text;
return button;
}
}
const myButton = new ButtonComponent('Click me');
document.body.appendChild(myButton.render());
使用工厂函数实现组件
function createButton(text) {
const button = document.createElement('button');
button.textContent = text;
return {
element: button,
setText(newText) {
button.textContent = newText;
}
};
}
const button = createButton('Submit');
document.body.appendChild(button.element);
使用现代框架实现组件
React函数组件示例
import React from 'react';
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
Vue单文件组件示例
<template>
<div>
<h1>{{ greeting }}</h1>
<button @click="changeGreeting">Change</button>
</div>
</template>
<script>
export default {
data() {
return {
greeting: 'Hello World'
};
},
methods: {
changeGreeting() {
this.greeting = 'Hello Vue!';
}
}
};
</script>
组件通信模式
父子组件通信(React示例)
// Parent.js
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<Child count={count} onIncrement={() => setCount(c => c + 1)} />
</div>
);
}
// Child.js
function Child({ count, onIncrement }) {
return (
<div>
<p>Count: {count}</p>
<button onClick={onIncrement}>Increment</button>
</div>
);
}
事件总线模式(Vue示例)
// eventBus.js
import Vue from 'vue';
export const EventBus = new Vue();
// ComponentA.vue
EventBus.$emit('message', 'Hello from A');
// ComponentB.vue
EventBus.$on('message', (msg) => {
console.log(msg); // 'Hello from A'
});
组件生命周期管理
类组件生命周期(React)
class LifecycleDemo extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Lifecycle Demo</div>;
}
}
组合式API生命周期(Vue 3)
import { onMounted, onUpdated, onUnmounted } from 'vue';
export default {
setup() {
onMounted(() => {
console.log('Component mounted');
});
onUpdated(() => {
console.log('Component updated');
});
onUnmounted(() => {
console.log('Component will unmount');
});
}
};
组件样式封装
CSS Modules(React)
import styles from './Button.module.css';
function Button() {
return <button className={styles.primary}>Click</button>;
}
Scoped Styles(Vue)

<template>
<button class="primary">Click</button>
</template>
<style scoped>
.primary {
background: blue;
}
</style>
这些方法展示了从原生JavaScript到现代框架的组件实现方式,开发者可以根据项目需求选择合适的方法。组件化开发的核心思想是关注点分离和可复用性,良好的组件设计应该遵循单一职责原则。






