javascript - 不推荐在 ref 属性中使用字符串文字
问题描述
我在反应本机代码中这样做,eslint 显示行错误ref="drawer"
[eslint] 不推荐在 ref 属性中使用字符串文字。
这样做的正确方法是什么。
<DrawerLayoutAndroid
drawerWidth={300}
ref="drawer"
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}
</DrawerLayoutAndroid>
解决方案
您需要使用不推荐使用的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() 的等价物是什么
推荐阅读
- doctrine - ManyToMany Doctrine join 必须返回一行
- python - 在嵌套列表中查找具有最大数字的列表
- c++ - 为什么位操作不适用于 CSES 位字符串问题
- heroku - 业余爱好者测功机用完了测功机时间吗?
- ml.net - 使用 ml.net predictionEnginePool 时的 System.InvalidOperationException
- javascript - d3按弧线动画路径
- matlab - 如何更改平面中线图的颜色?
- java - 需要检查java中两个单词ae是否相等
- gcc - gcc有薄lto吗?
- google-chrome-extension - 无法在强制安装的 chrome 扩展中打开“检查”