示例
import { useEffect, useRef } from 'react';
import { View, Text, Platform } from 'react-native';
export function DomTest() {
const containerRef = useRef<any>(null);
useEffect(() => {
if (Platform.OS === 'web') {
// Web 平台: DOM 操作
const div = document.createElement('div');
div.textContent = '这是动态创建的文本';
div.style.color = 'blue';
containerRef.current?.appendChild(div);
}
}, []);
if (Platform.OS !== 'web') {
// 原生平台: 使用 React Native 组件
return (
<View style={{ padding: 10 }}>
<Text style={{ color: 'blue' }}>
这是原生组件显示的文本
</Text>
</View>
);
}
// Web 平台: 返回一个 div 容器
return (
<div ref={containerRef} style={{ padding: 10 }}>
<p>这是初始文本</p>
</div>
);
}