gpt4 book ai didi

javascript - ReactNative 错误 onPress

转载 作者:行者123 更新时间:2023-11-30 15:09:55 28 4
gpt4 key购买 nike

单击文本时,我收到一条错误消息“undefined is not an object (evaluating '_this2.categoryClicked.bind')”

我认为错误是“onPress={()=>this.categoryClicked.bind(this)}”,单击按钮时必须以不同的方式调用 categoryClicked 函数。我的代码有什么问题?

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>
)
}
}

最佳答案

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

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

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

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

如果你想传递sub-category,你可以这样做

constructor(props) {
super(props);

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

然后在render中这样使用:

this.props.Category.sub_category.map(function(subCategory, i) {
<View style={styles.abcd}>
<TouchableHighlight onPress={this.subcategoryClicked[i]}>
<Text>{subCategory.title}</Text>
</TouchableHighlight>
</View>

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

关于javascript - ReactNative 错误 onPress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45261615/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com