在单击文本时,我收到一个错误消息:“未定义的不是对象(计算'_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>
)
}
}发布于 2017-07-23 13:55:11
我相信你想做的是onPress={this.categoryClicked.bind(this)}而不是箭头函数。.bind(this)返回一个上下文正确绑定到this的函数,因此,它不会被调用。
此外,我建议将绑定放在构造函数中,因为您不希望每次组件重新呈现时都发生绑定。例如:
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>另外,我不确定这是不是一个好的模式。如果您不习惯这样做,请坚持使用this.categoryClicked(bind, subcategory)。这是我不确定优化是否值得的事情之一。
发布于 2017-07-23 13:04:59
这在onPress={()=>this.categoryClicked.bind(this)}>中指向sub_category.map函数。相反,它应该指向类。可以用这种方式来完成
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方法中应该是可访问的
categoryClicked(category){
this.props.categoryPressed(category);
}https://stackoverflow.com/questions/45261615
复制相似问题