Why Is Ref Not A Property In Children Components?
Solution 1:
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
constref = React.createRef();
and then you pass it to your component as shown below:
<FancyButtonforwardedRef={ref}text="Click ME!" />
where inside the FancyButton
the ref will be available as
<buttononClick={() => {
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
Solution 2:
ref does not behave like a regular props. It has a special meaning.
classAextendsReact.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.
Post a Comment for "Why Is Ref Not A Property In Children Components?"