最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing Props from React Ref Object - Stack Overflow

programmeradmin1浏览0评论

Is there a way to access props or data-attributes on the ref object of a react ponent. I have been digging through the ponent and haven't found anything. Ideally I would like to access the prop valid that I have passed to it. I would be willing to get the data another way but ideally in the ref object if possible.

Is there a way to access props or data-attributes on the ref object of a react ponent. I have been digging through the ponent and haven't found anything. Ideally I would like to access the prop valid that I have passed to it. I would be willing to get the data another way but ideally in the ref object if possible.

Share Improve this question edited Apr 21, 2020 at 15:03 jonrsharpe 122k30 gold badges267 silver badges474 bronze badges asked Apr 21, 2020 at 15:01 Josh BowdenJosh Bowden 1,3525 gold badges15 silver badges31 bronze badges 3
  • 1 post some code showing what you mean and have tried – user120242 Commented Apr 21, 2020 at 15:04
  • I can't show the object exactly. I will see if I can make a working codepen demo – Josh Bowden Commented Apr 21, 2020 at 15:05
  • Does the react ref object give access to props of the ponent in any way – Josh Bowden Commented Apr 21, 2020 at 15:10
Add a ment  | 

2 Answers 2

Reset to default 3

React refs are a great way to get a reference to the DOM element rendered by a react ponent, so you don't actually have access to the ponent thru refs, just the latest snapshot of what the ponent printed to the DOM. Have a look at the docs here. You do, however, have access to DOM data attributes. Here's an example of how that works. (note: this is not a good way to flow data thru the app)

import React from "react";

const CustomDiv = ({ customRef, someProp }) => <div ref={customRef} data-custom-attr={someProp} />;

export default function App() {
    const customRef = React.createRef();

    const clicked = () => {
        console.log(customRef.current);
        console.log(customRef.current.getAttribute("data-custom-attr"));
    };

    return (
        <div className="App">
            <CustomDiv customRef={customRef} someProp={"21"} />
            <button onClick={clicked}>Click Me</button>
        </div>
    );
}

And the console log after clicking the button will look like:

<div data-custom-attr="21"></div>
21 

You can check out the working example here.

Hope that helps.

Cheers!

发布评论

评论列表(0)

  1. 暂无评论