react-native - 这个 refs 在方法中变得未定义

标签 react-native

我想在我的项目中使用这个插件 https://github.com/rt2zz/react-native-drawer .我可以正确运行该示例,但在集成它时遇到问题。

我在方法 openDrawer 中遇到错误。 “无法读取未定义的属性抽屉”

我猜我没有以正确的方式定义和使用该类(我是 javascript OOP 的新手),例如它使用 React.createClass({不像我的扩展组件和构造函数。

我类的相关代码如下。

class Search extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: new ListView.DataSource({
               rowHasChanged: (row1, row2) => row1 !== row2
            })
        };
    }

    openDrawer(){
        this.refs.drawer.open()
    }

    getInitialState(){
        return {
          drawerType: 'overlay',

        }
    }

渲染是
render() {
        if (this.state.isLoading) {
            return this.renderLoadingView();
        }

        var controlPanel = <MyControlPanel closeDrawer={() => {this.refs.drawer.close()}} />

        return (


            <View>
                <View style={styles.topBar}>

                    <Drawer
                        ref="drawer"
                        >
                        <MyMainView
                          />
                    </Drawer>

                    <Text style={styles.topBarMenu}>&#9776;</Text>
                    <Text style={styles.topBarTitle}>เงินปันผล</Text>
                    <Text style={styles.topBarRight}></Text>
                </View>

最佳答案

有比放置 this.openDrawer = this.openDrawer.bind(this) 更好的方法在构造函数中
使用箭头函数声明 openDrawer 方法:

openDrawer = () => {
  this.refs.drawer.open()
}

关于react-native - 这个 refs 在方法中变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31986126/

相关文章:

javascript - react native : Conditional Render not working as it should

react-native - 在 AsyncStorage 中 setItem 的正确方法

Firebase messaging.getToken() 失败并出现 MISSING_INSTANCEID_SERVICE 错误

typescript - 在 native react 中创建下拉菜单

react-native - 本地计划通知 native 响应

javascript - 在 React-native 应用程序中使用 Fable 中的 native 模块

react-native - 说请将方法附加到此组件

android - 为 android 和 ios react native 指纹认证

javascript - 当 firebase 数据存储到对象时获取未定义

javascript - 如何在 React Native 中的单选按钮中提供 fetch api?