score:2

Accepted answer

is there a explanation about this?

the issue you are seeing is due to the fact that key and ref are special props. see

most props on a jsx element are passed on to the component, however, there are two special props (ref and key) which are used by react, and are thus not forwarded to the component.

for instance, attempting to access this.props.key from a component (i.e., the render function or proptypes) is not defined. if you need to access the same value within the child component, you should pass it as a different prop (ex: <listitemwrapper key={result.id} id={result.id} />). while this may seem redundant, it’s important to separate app logic from reconciling hints.

to access ref in child pass it in a different prop. say you create a ref like

const ref = react.createref();

and then you pass it to your component as shown below:

<fancybutton forwardedref={ref} text="click me!" />

where inside the fancybutton the ref will be available as

 <button
      onclick={() => {
        this.logref(forwardedref);
      }}
      ref={forwardedref}
    >
      {text}
 </button>

where logref is defined as

logref(myref) {
    console.log(myref.current);
}

a working example can be seen at (click on the button and check the console) : https://codesandbox.io/s/ko6wnrorv

score:0

ref does not behave like a regular props. it has a special meaning.

class a extends react.component{
    render(){
        return <b
            ref={ref=>this.bref = ref} 
        />
    }
}

what it means here is, you are getting a reference of component 'b' in component 'a'. that is, you can use this.bref to call some methods in component 'b' from component 'a'

note: this.bref will get it's value only after a and b is rendered until then it will be undefined.


Related Query

More Query from same tag