问题
In React quickstart, it is stated about Refs and Functional Components
that
You may not use the ref attribute on functional components because they don't have instances:
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
render() {
// This will *not* work!
return (
<MyFunctionalComponent
ref={(input) => { this.textInput = input; }} />
);
}
}
I don't fully understand the above statement and the example. So far from reading the tutorials, the only difference between functional and class component is that the latter can have things like constructor and lifecycle management functions.
What does the documentation mean when it says functional components don't have instances? Is it because they don't have this
pointer? Is this restriction coming from react or ES6?
回答1:
Functional components are re-rendered from top to bottom on each virtual DOM update. Since they are simple pure function, they just accept properties and output a piece of virtual DOM. Their lifespan is limited to a single render.
Default React components extend React.component class, so they inherit features like lifecycle hooks and internal state management. Those features allow the component to keep their state between renders and to behave accordingly. In that sense, I would call them components which have an instance.
回答2:
I faced the same doubt while reading the docs on ref. However, after doing a little more research I found this discussion. (https://github.com/facebook/react/issues/4936#issuecomment-142379068)
Functional components don't have instances because they are mere JS functions. A function can't have an instance. Whereas, classes have instances(objects) of them.
So when the documentation says you can't use ref on functional components because they don't have instances means that -> how can you store the instance of a functional component when it doesn't exist?
来源:https://stackoverflow.com/questions/44478809/why-do-functional-component-in-reactjs-not-have-instances