react 如何html5
React 中使用 HTML5 的功能
在 React 中集成 HTML5 功能,可以通过直接使用 HTML5 标签或结合 React 的 API 实现。以下是常见 HTML5 功能在 React 中的实现方式。
使用 HTML5 视频和音频标签
React 支持直接使用 <video> 和 <audio> 标签,通过 ref 控制媒体播放。

import React, { useRef } from 'react';
function MediaPlayer() {
const videoRef = useRef(null);
const playVideo = () => {
videoRef.current.play();
};
return (
<div>
<video ref={videoRef} width="400" controls>
<source src="example.mp4" type="video/mp4" />
</video>
<button onClick={playVideo}>Play</button>
</div>
);
}
使用 Canvas 绘图
通过 useRef 获取 Canvas 的 DOM 节点,结合 useEffect 在组件挂载后绘制图形。
import React, { useRef, useEffect } from 'react';
function CanvasDraw() {
const canvasRef = useRef(null);
useEffect(() => {
const ctx = canvasRef.current.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 50);
}, []);
return <canvas ref={canvasRef} width="200" height="200" />;
}
使用地理定位 API
通过 navigator.geolocation 获取用户位置,注意浏览器兼容性和用户授权。

import React, { useState } from 'react';
function Geolocation() {
const [location, setLocation] = useState(null);
const getLocation = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
setLocation({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
},
(error) => console.error(error)
);
};
return (
<div>
<button onClick={getLocation}>Get Location</button>
{location && (
<p>
Latitude: {location.lat}, Longitude: {location.lng}
</p>
)}
</div>
);
}
使用本地存储
通过 localStorage 或 sessionStorage 存储数据,结合 useEffect 和 useState 管理状态。
import React, { useState, useEffect } from 'react';
function LocalStorageExample() {
const [name, setName] = useState('');
useEffect(() => {
const storedName = localStorage.getItem('name');
if (storedName) setName(storedName);
}, []);
const saveName = () => {
localStorage.setItem('name', name);
};
return (
<div>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button onClick={saveName}>Save</button>
</div>
);
}
使用拖放 API
通过 draggable 属性和事件处理器实现拖放功能。
import React, { useState } from 'react';
function DragDrop() {
const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);
const [draggedItem, setDraggedItem] = useState(null);
const handleDragStart = (index) => {
setDraggedItem(index);
};
const handleDragOver = (index) => {
if (draggedItem === null || draggedItem === index) return;
const newItems = [...items];
const item = newItems[draggedItem];
newItems.splice(draggedItem, 1);
newItems.splice(index, 0, item);
setItems(newItems);
setDraggedItem(index);
};
return (
<div>
{items.map((item, index) => (
<div
key={index}
draggable
onDragStart={() => handleDragStart(index)}
onDragOver={() => handleDragOver(index)}
style={{ padding: '10px', margin: '5px', backgroundColor: 'lightgray' }}
>
{item}
</div>
))}
</div>
);
}
注意事项
- 事件处理:React 使用合成事件系统,与原生 DOM 事件略有不同,但大多数 HTML5 API 可以直接使用。
- 性能优化:频繁操作 DOM(如 Canvas 绘图)时,避免不必要的重渲染。
- 兼容性:某些 HTML5 功能(如地理定位)需要用户授权或特定浏览器支持。





