简体   繁体   English

有没有办法在 React 中访问嵌套的 DOM 元素?

[英]Is there a way to access nested DOM Elements in React?

In my app, I have an input field and a ref that stores the value of the user input.在我的应用程序中,我有一个输入字段和一个存储用户输入值的 ref。 I also have a bunch of React Links in a div that serve as recommended keywords for the user to search.我还在一个 div 中有一堆 React Links,它们作为推荐的关键字供用户搜索。

Is there a way for me to dynamically modify the React Link element that has the same text as the user input?有没有办法让我动态修改与用户输入具有相同文本的 React Link 元素?

EG: user inputs "shoe" and there's a <Link to="/display?shoe"> Shoe </Link> , then I can get that element and add some inline css to it. EG:用户输入“shoe”并且有一个<Link to="/display?shoe"> Shoe </Link> ,然后我可以获取该元素并添加一些内联 css 到它。

Snippet片段

In React you can access the DOM element using Refs.在 React 中,您可以使用 Refs 访问 DOM 元素。

Creating Refs: create using React.createRef() and attach it to the React elements using ref attribute.创建 Refs:使用 React.createRef() 创建并使用 ref 属性将其附加到 React 元素。

This can be done if you store the user input in state.如果您将用户输入存储在 state 中,则可以做到这一点。 So whenever state changes the Link is updated因此,每当 state 更改时, Link都会更新

Example:例子:

const [userInput, setUserInput] = useState(''); // store input value
<Link to=`/display?${userInput}`>{userInput}</Link>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM