###前提・実現したいこと
現在ReactNativeを使いカード形式のカスタムコンポーネントを作っています。
その中でこのカードをタップした場合に親コンポーネントの関数を呼び出すことのできる機能を実装しようとしてるのですがなかなかできません。
###発生している問題・エラーメッセージ
状況としましては親コンポーネント内で以下のように実装したカスタムコンポーネント(Card)をクリックすると
js
1import Card from './Card' 2 3export default class ParentComponent extends React.Component { 4 constructor(props) { 5 super(props); 6 this.state = { 7 }; 8 } 9 _onPress() { 10 console.log('タップ確認') 11 } 12 render () { 13 return ( 14 <Card onPress={() => this._onPress()} /> 15 ) 16 } 17}
以下のようなエラーが発生してしまいParentComponentの_onPress()が呼ばれませんでした。
undefined is not a function (evaluating '_this2._onPress()')
###該当のソースコード
js
1import React from 'react' 2import { 3 View, 4 Alert, 5} from 'react-native' 6 7import Card from './Card' 8 9export default class ParentComponent extends React.Component { 10 constructor(props) { 11 super(props); 12 this.state = { 13 }; 14 } 15 _onPress() { 16 console.log('タップ確認') 17 } 18 render () { 19 return ( 20 <View> 21 <Card onPress={() => this._onPress()} /> 22 </View> 23 ) 24 } 25}
js
1import React from 'react' 2import { 3 View, 4 Alert, 5 TouchableHighlight, 6 Text 7} from 'react-native' 8 9 10export default class Card extends React.Component { 11 constructor(props) { 12 super(props); 13 this.state = { 14 }; 15 } 16 _onPress() { 17 console.log('タップ確認') 18 } 19 render () { 20 return ( 21 <TouchableHighlight underlayColor={'#f3f3f2'} 22 onPress={this.props.onPress}> 23 <View><Text>カード</Text></View> 24 </TouchableHighlight> 25 ) 26 } 27}
###試したこと
エラー文からおそらくCardコンポーネント内のthis.props.onPress関数が親コンポーネントのonPress()を正しく呼出せてないのが原因かと思い
onPress().bind(this)を使ってみたりアロー文を消して関数だけを記述してみたのですが同様のエラーが出てしまい解決できませんでした。
おそらく関数のリンク付けの問題だと思うのですが、解決策が分かりませんでした。
よろしくお願いします
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/03/13 09:36