【问题标题】:Using string literals in ref attributes is deprecated不推荐在 ref 属性中使用字符串文字
【发布时间】:2018-11-03 09:17:14
【问题描述】:

我在 react native 代码中这样做,eslint 显示行 ref="drawer" 的错误

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

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

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

【问题讨论】:

    标签: javascript reactjs react-native eslint


    【解决方案1】:

    您需要将ref callback pattern 用作string refs are deprecated.

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

    (ref) =&gt; this.drawer = ref是一个箭头函数语法,你可以把它简化成类似

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

    查看此答案了解更多信息

    How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

    【讨论】:

    • 我是js新手,你能解释一下这个语法吗?
    • @Khemraj,这是箭头函数语法,检查更新
    【解决方案2】:

    你可以用花括号将它们包裹起来,以表明它是有效的 JS 语法

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

    【讨论】:

    • 即使加了花括号 es-lint 错误也会显示一样
    • @TinoJoseThannippara:我很确定他们不会,但这可能是由于您的代码编辑器需要一些时间来刷新。您可以尝试重新打开页面
    • 问题是询问正确的方法来解决 eslint 显示的错误,而不是如何解决 eslint 规则
    猜你喜欢
    • 2020-09-30
    • 2014-04-21
    • 1970-01-01
    • 2012-03-27
    • 2018-03-10
    • 2012-11-21
    • 2015-10-22
    • 2016-10-10
    相关资源
    最近更新 更多