How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

前端 未结 4 1789
面向向阳花
面向向阳花 2020-11-22 05:34

How do I select certain bars in react.js?

This is my code:

var Progressbar = React.createClass({
    getInitialState: function () {
        return {          


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-22 06:26

    You can do that by specifying the ref

    EDIT: In react v16.8.0 with functional component, you can define a ref with useRef. Note that when you specify a ref on a functional component, you need to use React.forwardRef on it to forward the ref to the DOM element of use useImperativeHandle to to expose certain functions from within the functional component

    Ex:

    const Child1 = React.forwardRef((props, ref) => {
        return 
    Child1
    }); const Child2 = React.forwardRef((props, ref) => { const handleClick= () =>{}; useImperativeHandle(ref,() => ({ handleClick })) return
    Child2
    }); const App = () => { const child1 = useRef(null); const child2 = useRef(null); return ( <> ) }

    EDIT:

    In React 16.3+, use React.createRef() to create your ref:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
      render() {
        return 
    ; } }

    In order to access the element, use:

    const node = this.myRef.current;
    

    DOC for using React.createRef()


    EDIT

    However facebook advises against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

    From the docs:

    Legacy API: String Refs

    If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

    A recommended way for React 16.2 and earlier is to use the callback pattern:

     {this.Progress[0] = input }}/>
    
    

    {this.Progress[1] = input }}/>

    {this.Progress[2] = input }}/>

    DOC for using callback


    Even older versions of react defined refs using string like below

    
    
        

    In order to get the element just do

    var object = this.refs.Progress1;
    

    Remember to use this inside an arrow function block like:

    print = () => {
      var object = this.refs.Progress1;  
    }
    

    and so on...

提交回复
热议问题