2017-05-26 7 views
0

子コンポーネント内の親コンポーネントにある関数を呼び出そうとしていますが、ワーキング。React Native:子コンポーネントの親コンポーネントの関数を呼び出す際に問題が発生しました。

今私は現在、このエラーを取得しています: E ReactNativeJS: { [TypeError: undefined is not a function (evaluating '_this.props.setModalVisible(false)')]

私はSO上で同様の質問を見てきましたが、それを把握することはできません。どんな助けでも大歓迎です!

私の親コンポーネントのコード:

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 } />; 

私の子コンポーネントのコード:

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

答えて

1
<Button onPress={() => this.handlePress(this.props.setModalVisible) }>View Thing</Button> 

は、別の関数の引数として関数を渡すための正しい方法ではありません、あなたは「ドンそれも必要なのです。あなたは、いくつかの引数を指定して親関数を呼び出しているとき、あなたは

return <Child setModalVisible={(val) => this.setModalVisible(val) } />; 
+0

Hrmでもエラーが発生します: '[TypeError:undefinedは関数ではありません( '_this2.setModalVisible(val)'を評価しています)]'私は、見てください:https://gist.github.com/chapeljuice/ea57a25f6e8366527a6bae78f3c9d98c – chapeljuice

+0

エラーを見つけるのは難しいですが、どのラインまたはエラーポイントを置くことができます –

+0

はいもちろん、それはchild.jsの行69です要点 – chapeljuice

0

のように親からそれを渡す必要がちょうどFYIそれはスコープの問題だった、と私は持っている。また

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

ようにそれを行うことができますそれを固定して以来。私はまだエラーが発生しており、parent.jsの36行目と40行目の関数を矢印関数に変更したときに修正されました。

関連する問題