如何在reactJs中点击标题文本



我有多个框,我想在点击按钮时获得标题文本。现在我可以只按一下文字了。我该怎么做?

我的代码:-

const Forms = () => {
const  boxStyle = {
backgroundColor: 'gray',
padding:'10px',
marginBottom:'15px'
}
const handleClick =( event) => {
const theText = event.target.textContent;

console.log("the text: ", theText);
};
return (
<div>
<div className="box" style={boxStyle}>
<h2>Heading 1</h2>
<button onClick={handleClick}>click</button>
</div>

<div className="box" style={boxStyle}>
<h2>Heading 2</h2>
<button onClick={handleClick}>click</button>
</div>
</div>
);
};
ReactDOM.render(<Forms />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

谢谢你的努力!

请检查一下,它对我有效。

const Forms = () => {
const  boxStyle = {
backgroundColor: 'gray',
padding:'10px',
marginBottom:'15px'
}
const handleClick =( event) => {

const theText = event.target.closest(".box").querySelector("h2").textContent;
console.log("the text: ", theText);
};
return (
<div>
<div className="box" style={boxStyle}>
<h2>Heading 1</h2>
<button onClick={handleClick}>click</button>
</div>

<div className="box" style={boxStyle}>
<h2>Heading 2</h2>
<button onClick={handleClick}>click</button>
</div>
</div>
);
};
ReactDOM.render(<Forms />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

您可以通过将ref添加到标签并从ref中获取文本来完成。

https://reactjs.org/docs/refs-and-the-dom.html

最新更新