繁体   English   中英

不知道我在做什么错-获取不是函数错误

[英]Not sure what I am doing wrong - getting is not a function errors

我不确定自己在做什么错,但是我的组件中有一些功能。 但是,我无法将这些功能之一作为道具传递,我收到了this.nextScene不是一个功能。

这是我组件的摘录,我已经注释掉了问题所在:

  nextScene() {
    this.refs.navigator.push('browse');
  }

  renderNavigationView() {
    return (
      <View style={styles.drawer}>
        <Touchable
          onPress={this.nextScene()}     //issue here, "this.nextScene is not a function"
        >
          <View style={styles.container}>
            <Text style={styles.title}>Browse</Text>
          </View>
        </Touchable>
        <Touchable>
          <View style={styles.container}>
            <Text style={styles.title}>Button</Text>
          </View>
        </Touchable>
      </View>
    );
  }

  render() {
    return (
      <DrawerLayoutAndroid
        ref="drawer"
        drawerWidth={300}
        drawerPosition={DrawerLayoutAndroid.positions.Left}
        renderNavigationView={this.renderNavigationView}>
        <Navigator
          ref="navigator"
          configureScene={(route) => {
            if (Platform.OS === 'android') {
              return Navigator.SceneConfigs.FloatFromBottomAndroid;
            }
          } }
          initialRoute={{}}
          renderScene={this.renderScene}
          />
      </DrawerLayoutAndroid>
    );
  }

谢谢!

如果您查看正在渲染的组件和renderNavigationView

renderNavigationView={this.renderNavigationView}

这似乎很好,但由于this方面的功能是window在默认情况下, this指的是windowrenderNavigationView 考虑您的onPress事件处理程序:

onPress={this.nextScene()}

由于您使用this.nextScene()this指的是window中的函数,你有效地试图做window.nextScene不存在,从而引发错误。 (还请注意,这是一个调用,而不是引用。请删除括号)。


因此,如果我尝试this.nextScene.bind(this)this.nextScene.bind(this)得到cannot read property 'bind' of undefined

这是因为该函数未定义,因为window.nextScene不存在。 为了解决这个问题,使用Function.prototype.bind绑定的this正确双方 renderNavigationViewnextScene

renderNavigationView={this.renderNavigationView.bind(this)}

在这种情况下, bind作用是在函数中设置this上下文。 由于this这里指的是类,类将被用于执行nextScene方法,它应该正常工作。 您还必须在nextScene上使用bind,因为在nextScene内部,我们希望this引用 ,而不是window

onPress={this.nextScene.bind(this)} 

温特在回答中指出的使用bind方法的另一种替代方法是使用箭头函数, this函数会自动将其绑定到父上下文。

class MyComponent extends React.Component {
  clickHandler = (e) => {
    // do stuff here
  }

  render() {
    return (
      <button onClick={this.clickHandler}></button>
    )
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM