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

前端 未结 4 1787
面向向阳花
面向向阳花 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:16

    For getting the element in react you need to use ref and inside the function you can use the ReactDOM.findDOMNode method.

    But what I like to do more is to call the ref right inside the event

    <input type="text" ref={ref => this.myTextInput = ref} />
    

    This is some good link to help you figure out.

    0 讨论(0)
  • 2020-11-22 06:16

    You can replace

    document.getElementById(this.state.baction).addPrecent(10);
    

    with

    this.refs[this.state.baction].addPrecent(10);
    
    
      <Progressbar completed={25} ref="Progress1" id="Progress1"/>
    
    0 讨论(0)
  • 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 <div ref={ref}>Child1</div> 
    });
    
    const Child2 = React.forwardRef((props, ref) => {
        const handleClick= () =>{};
        useImperativeHandle(ref,() => ({
           handleClick
        }))
        return <div>Child2</div> 
    });
    const App = () => {
        const child1 = useRef(null);
        const child2 = useRef(null);
    
        return (
            <>
               <Child1 ref={child1} />
               <Child1 ref={child1} />
            </>
        )
    }
    

    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 <div ref={this.myRef} />;
      }
    }
    

    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:

    <Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/>
    
    <h2 class="center"></h2>
    
    <Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/>
    
      <h2 class="center"></h2>
    
    <Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/>
    

    DOC for using callback


    Even older versions of react defined refs using string like below

    <Progressbar completed={25} id="Progress1" ref="Progress1"/>
    
        <h2 class="center"></h2>
    
        <Progressbar completed={50} id="Progress2" ref="Progress2"/>
    
          <h2 class="center"></h2>
    
        <Progressbar completed={75} id="Progress3" ref="Progress3"/>
    

    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...

    0 讨论(0)
  • 2020-11-22 06:29

    Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.

    Instead we can use React ref system to access and manipulate Dom as shown in below example:

    constructor(props){
    
        super(props);
        this.imageRef = React.createRef(); // create react ref
    }
    
    componentDidMount(){
    
        **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
    }
    
    
    render = (props) => {
    
    const {urls,description} = this.props.image;
        return (
    
                <img
                 **ref = {this.imageRef} // assign the ref of img tag here**
                 src = {urls.regular} 
                 alt = {description}
                 />
    
            );
    
    }
    

    }

    0 讨论(0)
提交回复
热议问题