I'm trying to use React.forwardRef, but tripping over how to get it to work in a class based component (not HOC).
The docs examples use elements and functional components, even wrapping classes in functions for higher order components.
So, starting with something like this in their ref.js
file:
const TextInput = React.forwardRef(
(props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />)
);
and instead defining it as something like this:
class TextInput extends React.Component {
render() {
let { props, ref } = React.forwardRef((props, ref) => ({ props, ref }));
return <input type="text" placeholder="Hello World" ref={ref} />;
}
}
or
class TextInput extends React.Component {
render() {
return (
React.forwardRef((props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />))
);
}
}
only working :/
Also, I know I know, ref's aren't the react way. I'm trying to use a third party canvas library, and would like to add some of their tools in separate components, so I need event listeners, so I need lifecycle methods. It may go a different route later, but I want to try this.
The docs say it's possible!
Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
from the note in this section.
But then they go on to use HOCs instead of just classes.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…