You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中ref属性用字符串字面量已弃用,正确写法是什么?

Fixing the "Using string literals in ref attributes is deprecated" ESLint Error in React Native

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:00:07