js实现组件
使用原生JavaScript实现组件
在原生JavaScript中创建组件可以通过自定义元素(Custom Elements)和Shadow DOM实现。以下是一个基础组件的实现示例:
class MyComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
padding: 16px;
border: 1px solid #ccc;
}
</style>
<div class="component-content">
<slot></slot>
</div>
`;
}
connectedCallback() {
console.log('Component added to DOM');
}
}
customElements.define('my-component', MyComponent);
使用React实现组件
React组件可以通过函数组件或类组件方式实现:
import React from 'react';
function FunctionalComponent(props) {
return (
<div className="functional-component">
<h3>{props.title}</h3>
<p>{props.children}</p>
</div>
);
}
class ClassComponent extends React.Component {
render() {
return (
<div className="class-component">
<h3>{this.props.title}</h3>
<p>{this.props.children}</p>
</div>
);
}
}
使用Vue实现组件
Vue单文件组件(SFC)的基本结构:
<template>
<div class="vue-component">
<h3>{{ title }}</h3>
<p><slot></slot></p>
</div>
</template>
<script>
export default {
name: 'VueComponent',
props: {
title: {
type: String,
default: 'Default Title'
}
}
}
</script>
<style scoped>
.vue-component {
border: 1px solid #42b983;
padding: 16px;
}
</style>
组件通信模式
父子组件通信通过props和events实现:
// 父组件
function ParentComponent() {
const handleChildEvent = (data) => {
console.log('Received from child:', data);
};
return <ChildComponent onCustomEvent={handleChildEvent} />;
}
// 子组件
function ChildComponent({ onCustomEvent }) {
const sendData = () => {
onCustomEvent({ message: 'Hello from child' });
};
return <button onClick={sendData}>Send Data</button>;
}
组件生命周期管理
React类组件生命周期方法示例:
class LifecycleComponent extends React.Component {
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate(prevProps) {
if (this.props.value !== prevProps.value) {
console.log('Value prop changed');
}
}
componentWillUnmount() {
console.log('Component will unmount');
}
}
组件状态管理
使用React Hooks管理状态:

import { useState, useEffect } from 'react';
function StatefulComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}






