无状态函数组件不能被赋予 refs
Stateless function components cannot be given refs
我尝试访问组件中的一些引用。但是我在控制台中有这个错误。
withRouter.js:44 Warning: Stateless function components cannot be given refs (See ref "pseudo" in FormInputText created by RegisterForm). Attempts to access this ref will fail.
这是我的组件:
class RegisterForm extends React.Component {
render() {
return (
<form action="">
<FormInputText ref="pseudo" type="text" defaultValue="pseudo"/>
<input type="button" onClick={()=>console.log(this.refs);} value="REGISTER"/>
</form>
);
}
}
此外,当我单击按钮时,我在控制台中得到 Object {pseudo: null}
。我希望有一个对象 null
.
我不确定为什么这不起作用。请注意,我的反应树使用 mobx-react
.
引用不适用于无状态组件。 the docs
中有说明
Because stateless functions don't have a backing instance, you can't attach a ref to a stateless function component.
无状态组件在编写时实际上有实例(它们在内部被包装到 类 中)但是你不能访问它们,因为 React 团队将在未来进行优化。参见 https://github.com/facebook/react/issues/4936#issuecomment-179909980
您也可以尝试使用 recompose it has a function called toClass。
Takes a function component and wraps it in a class. This can be used as a fallback for libraries that need to add a ref to a component, like Relay.
If the base component is already a class, it returns the given component.
我尝试访问组件中的一些引用。但是我在控制台中有这个错误。
withRouter.js:44 Warning: Stateless function components cannot be given refs (See ref "pseudo" in FormInputText created by RegisterForm). Attempts to access this ref will fail.
这是我的组件:
class RegisterForm extends React.Component {
render() {
return (
<form action="">
<FormInputText ref="pseudo" type="text" defaultValue="pseudo"/>
<input type="button" onClick={()=>console.log(this.refs);} value="REGISTER"/>
</form>
);
}
}
此外,当我单击按钮时,我在控制台中得到 Object {pseudo: null}
。我希望有一个对象 null
.
我不确定为什么这不起作用。请注意,我的反应树使用 mobx-react
.
引用不适用于无状态组件。 the docs
中有说明Because stateless functions don't have a backing instance, you can't attach a ref to a stateless function component.
无状态组件在编写时实际上有实例(它们在内部被包装到 类 中)但是你不能访问它们,因为 React 团队将在未来进行优化。参见 https://github.com/facebook/react/issues/4936#issuecomment-179909980
您也可以尝试使用 recompose it has a function called toClass。
Takes a function component and wraps it in a class. This can be used as a fallback for libraries that need to add a ref to a component, like Relay.
If the base component is already a class, it returns the given component.