首页 > 解决方案 > 不推荐在 ref 属性中使用字符串文字

问题描述

我在反应本机代码中这样做,eslint 显示行错误ref="drawer"

[eslint] 不推荐在 ref 属性中使用字符串文字。

这样做的正确方法是什么。

<DrawerLayoutAndroid
                drawerWidth={300}
                ref="drawer"
                drawerPosition={DrawerLayoutAndroid.positions.Left}
                renderNavigationView={() => navigationView}
            </DrawerLayoutAndroid>

标签: javascriptreactjsreact-nativeeslint

解决方案


您需要使用不推荐使用的ref callback pattern字符串引用。

<DrawerLayoutAndroid
            drawerWidth={300}
            ref={(ref) => this.drawer = ref}
            drawerPosition={DrawerLayoutAndroid.positions.Left}
            renderNavigationView={() => navigationView}
        </DrawerLayoutAndroid>

(ref) => this.drawer = ref是箭头函数语法,您可以将其简化为

constructor(props) {
   super(props); 
   this.setRef = this.setRef.bind(this);
}
setRef(ref) {
   this.setRef = ref;
}

...
ref={this.setRef}

检查此答案以获取更多信息

如何在 React 中访问 DOM 元素?React 中 document.getElementById() 的等价物是什么


推荐阅读