gpt4 book ai didi

javascript - React Hooks 尝试在数组 ref 中使用 useState

转载 作者:行者123 更新时间:2023-11-29 10:26:31 24 4
gpt4 key购买 nike

我正在尝试在 React 中使用 Hooks,但我对 useState 和 References 有疑问。我的问题是因为我想在我的 jsx 中创建多个引用,但我不知道如何像数组一样使用使用状态,以及如何插入使用状态数据。

import React, { useState, useEffect } from "react";
import { Row, Col, Image, ListGroup, Container } from "react-bootstrap";
import AOS from "aos";
import "./css/App.css";
import "aos/dist/aos.css";
import Skills from "./Components/Skills";
import Work from "./Components/Work";

const App = () => {
const [ref, setRef] = useState([]);

useEffect(() => {
AOS.init({
duration: 2000
});
});

function handleOnClick(event) {
ref.scrollIntoView();
}

return (
<div className="App">
<Row>
<Col className="menu text-center" lg={4}>
<div className="picture">
<Image
src={process.env.PUBLIC_URL + "/Images/picture.jpg"}
roundedCircle
/>
</div>

<h1 className="menu-name">Fulanito Detal</h1>

<h4 className="menu-office">Software Engineer - Web Developer</h4>

<div>
<Row>
<Col lg={3}></Col>
<Col lg={6} className="menu-text">
<ListGroup>
<ListGroup.Item
onClick={event => handleOnClick(event)}
active
>
ABOUT
</ListGroup.Item>
<ListGroup.Item>WORK EXPERIENCE</ListGroup.Item>
<ListGroup.Item>EDUCATION</ListGroup.Item>
<ListGroup.Item>SKILLS</ListGroup.Item>
<ListGroup.Item>CONTACT</ListGroup.Item>
</ListGroup>
</Col>
<Col lg={3}></Col>
</Row>
</div>
</Col>

<Col className="info text-center" lg={8}>
<Container>
<div className="about"></div>

<div
className="work"
ref={ref => {
setRef(ref);
}}
>
<Work />
</div>

<div className="education"></div>

<div
className="skills"
ref={ref => {
setRef(ref);
}}
>
<Skills />
</div>

<div className="contact"></div>
</Container>
</Col>
</Row>
</div>
);
};

export default App;

ref 只用一个就可以正常工作。如果点击重定向到技能,但我想使用像数组这样的状态来处理所有引用,但我坚持使用这个。感谢您的帮助!

最佳答案

这是使用 useRef 的简化示例钩子(Hook):

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
const work = React.useRef();
const skills = React.useRef();

return (
<div>
<button onClick={() => work.current.scrollIntoView()}>
WORK EXPERIENCE
</button>
<button onClick={() => skills.current.scrollIntoView()}>SKILLS</button>
<div className="another" />
<div className="work" ref={work}>
WORK SECTION
</div>
<div className="skills" ref={skills}>
SKILL SECTIONS
</div>
</div>
);
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit react-use-ref-scroll

关于javascript - React Hooks 尝试在数组 ref 中使用 useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57839109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com