[英]React Native: Having an issue calling a function of a parent component from a child
I'm having an issue where I'm trying to call a function that's located in a parent component from inside the child component, but it's just not working. 我在尝试从子组件内部调用位于父组件中的函数时遇到问题,但它不起作用。
Right now I'm currently getting this error: E ReactNativeJS: { [TypeError: undefined is not a function (evaluating '_this.props.setModalVisible(false)')]
现在,我目前正在收到此错误:
E ReactNativeJS: { [TypeError: undefined is not a function (evaluating '_this.props.setModalVisible(false)')]
I've looked at similar questions on SO, but can't figure it out. 我已经在SO上看过类似的问题,但无法弄清楚。 Any help would be much appreciated!
任何帮助将非常感激!
My Parent component's code: 我的父母组件的代码:
constructor (props) {
super(props)
this.setModalVisible = this.setModalVisible.bind(this)
this.state = {
modalVisible: false,
}
}
setModalVisible = (visible) => {
this.setState({modalVisible: visible});
}
...
return <Child setModalVisible={ this.setModalVisible } />;
My Child component's code: 我的孩子组件的代码:
handlePress = ( setModalVisible ) => {
this.lookUp(setModalVisible);
}
lookUp = (setModalVisible) => {
fetch('https://example.com/path/that/works' )
.then( (response) => {
if(response.ok) {
// TRYING TO MAKE THIS WORK
this.props.setModalVisible(false)
}
})
...
}
render () {
const { setModalVisible } = this.props
return (
<Button onPress={ () => this.handlePress( this.props.setModalVisible ) }>View Thing</Button>
)
}
<Button onPress={ () => this.handlePress( this.props.setModalVisible ) }>View Thing</Button>
is not a correct way to pass a function as an argument to another function, you don't even need it. 将函数作为参数传递给另一个函数的方法不是正确的,您甚至不需要它。 You can do it like
你可以做到
handlePress = ( ) => {
this.lookUp();
}
lookUp = () => {
fetch('https://example.com/path/that/works' )
.then( (response) => {
if(response.ok) {
this.props.setModalVisible(false)
}
})
...
}
render () {
const { setModalVisible } = this.props
return (
<Button onPress={ () => this.handlePress() }>View Thing</Button>
)
}
Also when you are calling a parent function with some argument, you need to pass it from parent like 另外,当您使用某些参数调用父函数时,您需要像这样从父对象传递它
return <Child setModalVisible={(val) => this.setModalVisible(val) } />;
Just FYI it was a scoping issue, and I have since fixed it. 仅供参考,这是一个范围界定的问题,此后我已经解决了。 I was still getting an error and it was fixed when I changed the functions on lines 36 and 40 of
parent.js
to arrow functions. 我仍然遇到错误,并且当我将
parent.js
第36和40行的功能更改为箭头功能时,该错误已修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.