首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReactNative错误onPress

ReactNative错误onPress
EN

Stack Overflow用户
提问于 2017-07-23 12:51:33
回答 2查看 951关注 0票数 1

在单击文本时,我收到一个错误消息:“未定义的不是对象(计算'_this2.categoryClicked.bind')”

我认为错误是"onPress={()=>this.categoryClicked.bind(this)}“,当按钮被单击时,肯定有不同的方式来调用categoryClicked函数。我的代码出了什么问题?

代码语言:javascript
复制
class CategoriesView extends React.Component {
  constructor(props){
    super(props)
  }

categoryClicked(){
    this.props.categoryPressed(this.props.Category);
}

renderSubCategory(){
    return(
        this.props.Category.sub_category.map(function(subCategory, i){
            return(
                <View style={styles.abcd}>
                    <TouchableHighlight onPress={()=>this.categoryClicked.bind(this)}>
                        <Text>{subCategory.title}</Text>
                    </TouchableHighlight>
                </View>
            )
        })
    )
}

render(){
    return(
        <View style={{flex:1}}>
            <View style={styles.avf}>
                <Text>{this.props.Category.heading}</Text>
            </View>
            <View style={styles.ddd}>
                {this.renderSubCategory()}
            </View>
        </View>
    )
 }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-23 13:55:11

我相信你想做的是onPress={this.categoryClicked.bind(this)}而不是箭头函数。.bind(this)返回一个上下文正确绑定到this的函数,因此,它不会被调用。

此外,我建议将绑定放在构造函数中,因为您不希望每次组件重新呈现时都发生绑定。例如:

代码语言:javascript
复制
constructor(props) {
  super(props);
  this.categoryClicked = this.categoryClicked.bind(this);
}

然后只需使用onPress={this.categoryClicked}

如果你想把sub-category传下去,你可以这样做

代码语言:javascript
复制
constructor(props) {
  super(props);

  this.subcategoryClicked = props.Category.sub_categories.map(sub_category => this.categoryClicked.bind(this, sub_category));
}

然后在render中像这样使用

代码语言:javascript
复制
this.props.Category.sub_category.map(function(subCategory, i) {
  <View style={styles.abcd}>
    <TouchableHighlight onPress={this.subcategoryClicked[i]}>
      <Text>{subCategory.title}</Text>
    </TouchableHighlight>
  </View>

另外,我不确定这是不是一个好的模式。如果您不习惯这样做,请坚持使用this.categoryClicked(bind, subcategory)。这是我不确定优化是否值得的事情之一。

票数 2
EN

Stack Overflow用户

发布于 2017-07-23 13:04:59

这在onPress={()=>this.categoryClicked.bind(this)}>中指向sub_category.map函数。相反,它应该指向类。可以用这种方式来完成

代码语言:javascript
复制
return (
  this.props.Category.sub_category.map((subCategory, i) => { // <--- this way context is preserved 
    // other lines
    onPress={()=>this.categoryClicked.bind(this, subCategory)}>
    // other lines
  })
);

categoryClicked方法中应该是可访问的

代码语言:javascript
复制
categoryClicked(category){
    this.props.categoryPressed(category);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45261615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档