如何获取h2标题标签的内容?类似处理input元素的方式
解决React中获取h2标签内容的问题
h2不是表单控件,onChange事件只会在输入类表单元素上触发,所以直接用onChange监听h2肯定没用,下面给你几种可行方案:
方案1:直接复用控制h2内容的state(最推荐)
如果h2的内容是由React state控制的,那你根本不需要额外监听,直接用对应的state变量就能拿到内容:
import { useState } from 'react'; function App() { const [h2Text, setH2Text] = useState("Text to target"); return ( <div> <h2>{h2Text}</h2> {/* 比如通过按钮修改h2内容,同时能直接拿到h2Text的值 */} <button onClick={() => setH2Text("更新后的h2内容")}>修改内容</button> <p>当前h2内容:{h2Text}</p> </div> ); }
方案2:用MutationObserver监听DOM变化
如果h2的内容是由外部代码修改的(比如非React的第三方库、直接操作DOM),可以用MutationObserver监听DOM内容的变化:
import { useEffect, useRef, useState } from 'react'; function App() { const [check, setCheck] = useState(""); const h2Ref = useRef(null); useEffect(() => { // 创建观察者实例 const observer = new MutationObserver((mutations) => { mutations.forEach(() => { if (h2Ref.current) { setCheck(h2Ref.current.textContent); } }); }); // 监听h2元素的内容变化 if (h2Ref.current) { observer.observe(h2Ref.current, { childList: true, subtree: true, characterData: true }); } // 组件卸载时停止监听 return () => observer.disconnect(); }, []); return ( <div> <h2 ref={h2Ref}>Text to target</h2> <p>实时获取的h2内容:{check}</p> {/* 模拟外部修改h2内容的操作 */} <button onClick={() => { h2Ref.current.textContent = "通过DOM修改的内容"; }}>手动修改h2</button> </div> ); }
方案3:把h2设为可编辑(支持用户直接编辑)
如果需要让用户直接编辑h2的内容,可以开启contentEditable属性,然后监听onInput事件(可编辑元素触发的是input事件而非change):
import { useState } from 'react'; function App() { const [check, setCheck] = useState("Text to target"); return ( <h2 contentEditable onInput={(e) => setCheck(e.currentTarget.textContent)} suppressContentEditableWarning={true} // 关闭React的默认警告 style={{ border: '1px solid #ccc', padding: '4px' }} // 加个样式提示可编辑 > {check} </h2> ); }
内容的提问来源于stack exchange,提问作者Mintee
相关产品推荐
相关产品推荐

