React Native中ref属性用字符串字面量已弃用,正确写法是什么?
Hey, that ESLint error is letting you know string-based refs like ref="drawer" are no longer recommended in React (and React Native) — they’ve been deprecated because of limitations like poor debuggability, inconsistent behavior with dynamic components, and performance drawbacks.
Here are the modern, recommended ways to rewrite your DrawerLayoutAndroid ref:
1. For Class Components
If you’re working with a class component, you have two solid options:
Option A: Callback Refs
This approach lets you directly assign the ref instance to a class property:
<DrawerLayoutAndroid drawerWidth={300} ref={(drawerInstance) => { this.drawer = drawerInstance; }} drawerPosition={DrawerLayoutAndroid.positions.Left} renderNavigationView={() => navigationView} />
Later, when you need to interact with the drawer (like opening it), use this.drawer.openDrawer() or any other DrawerLayoutAndroid method.
Option B: React.createRef() (React 16.3+)
This is a formal, built-in approach for class components:
First, initialize the ref in your component’s constructor:
constructor(props) { super(props); this.drawerRef = React.createRef(); }
Then attach it to your DrawerLayoutAndroid:
<DrawerLayoutAndroid drawerWidth={300} ref={this.drawerRef} drawerPosition={DrawerLayoutAndroid.positions.Left} renderNavigationView={() => navigationView} />
To use the ref later, access the current property:
this.drawerRef.current.openDrawer();
2. For Functional Components (with Hooks)
If you’re using functional components (the standard in modern React Native), use the useRef hook:
First, import useRef from React:
import { useRef } from 'react';
Then create the ref inside your component:
const drawerRef = useRef(null);
Attach it to your drawer component:
<DrawerLayoutAndroid drawerWidth={300} ref={drawerRef} drawerPosition={DrawerLayoutAndroid.positions.Left} renderNavigationView={() => navigationView} />
When you need to call drawer methods, use drawerRef.current (optional chaining avoids errors if the ref isn’t initialized yet):
drawerRef.current?.openDrawer();
Either of these approaches will resolve the ESLint error and follow React’s best practices for refs!
内容的提问来源于stack exchange,提问作者Khemraj Sharma

