伙計們,我需要你的幫助來解決一個問題。我最近在學習如何使用 React。問題是這樣的:我有三個 h2 元素,每個元素都有不同的 id 屬性。我要做的是創建一個串列,其中包含與 h2 元素一樣多的“a”元素。每個“a”元素都應具有指向相應 h2 元素的 href 屬性。
我向你展示了我試圖做的事情。使用我撰寫的代碼,串列仍然是空白的。
import logo from './logo.svg';
import './App.css';
import { Link } from "react-router-dom";
function App() {
const h2 = Array.from(document.getElementsByTagName('h2'));
const list = h2.map(element => {
return (
<li key={element.id}>
<Link to={`${element.id}`}>{element.innerHTML}</Link>
</li>
);
})
return (
<div className="App">
<h2 id="first">First item</h2>
<h2 id="second">Second item</h2>
<h2 id="Third">Third item</h2>
<h4>List of h2:</h4>
<ul>
{list}
</ul>
</div>
);
}
export default App;
你能告訴我我應該做什么或者我應該去研究什么概念嗎?
uj5u.com熱心網友回復:
上述解決方案存在兩個問題。
- 在第一次渲染之前獲取 H2。
#
在 ID 的重定向鏈接之前缺少附加。
這是解決方案。我使用a
了標簽而不是 react-router 的鏈接,但它會以類似的模式作業。
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [list, setList] = useState([]);
useEffect(() => {
// Added this in useEffect as we endup fetching h2s before they render if kept outside. Here they will be fetched post first render
const h2 = Array.from(document.getElementsByTagName("h2"));
const currentList = h2.map((element) => {
return (
<li key={element.id}>
<a href={`#${element.id}`}>{element.innerHTML}</a>
</li>
);
});
setList(currentList);
}, []);
return (
<div className="App">
<h2 id="first">First item</h2>
<h2 id="second">Second item</h2>
<h2 id="Third">Third item</h2>
<div style={{ height: "100vh" }}>Some space</div>
<h4>List of h2:</h4>
<ul>{list}</ul>
</div>
);
}
這是代碼和框的一個作業示例,我在中心添加了一個大 div 以使滾動可見。請向下滾動示例。
uj5u.com熱心網友回復:
用于useEffect
存盤text
ofh2
并從中創建鏈接,如下所示,
根據需要更改li
為Links
const { useState, useEffect } = React;
function App() {
const [h2Count, setH2Count] = useState([]);
useEffect(() => {
const noOfH2s = [...document.querySelectorAll("h2")];
setH2Count(noOfH2s.map((el) => ({ text: el.innerText, id: el.id })));
}, []);
const list = h2Count.map((element, id) => {
return <li key={id}>{`${element.text}-${element.id}`}</li>;
});
return (
<div className="App">
<h2 id="first">First item</h2>
<h2 id="second">Second item</h2>
<h2 id="Third">Third item</h2>
<h4>List of h2:</h4>
<ul>{list}</ul>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/529669.html
上一篇:在React中宣告函陣列件的問題