javascript - Accessing Props from React Ref Object - Stack Overflow

Is there a way to access props or data-attributes on the ref object of a react ponent. I have been digg

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!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742337304a4424906.html

相关推荐

  • javascript - Accessing Props from React Ref Object - Stack Overflow

    Is there a way to access props or data-attributes on the ref object of a react ponent. I have been digg

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信