我正在创建一个待办事项列表应用程序来学习 React Native。当我尝试将点击处理程序传递给子项目时,它说点击处理程序函数未定义。
这是相关代码。
constructor(props) {
super(props)
this.handleTodoPress = this.handleTodoPress.bind(this)
}
handleTodoPress (event) {
console.warn('Press handled')
}
renderItem ({section, item}) {
return <TodoItem onItemPress={this.handleTodoPress} title={item.title} description={item.description} completed={item.completed} />
}
如果我在 renderItem
中记录 handleTodoPress
,它会显示为未定义。这是为什么?
最佳答案
有几种方法可以解决这个问题,例如将 renderItem
放入构造函数中,就像 handleTodoPress
一样,或者您可以使用属性初始值设定项:
renderItem = ({section, item}) => {
return <TodoItem onItemPress={this.handleTodoPress} title={item.title} description={item.description} completed={item.completed} />
}
现在 this
将指向该组件并允许您使用 this.handleTodoPress
关于javascript - 函数未定义,尽管它是在之前声明的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49739350/