Реагировать на собственное событие TouchableOpacity onPress, не работающее при вызове из другого класса

Что я хотел сделать, так это создать TouchableOpacity один раз и использовать его везде в своей программе. Я устранил проблему при обработке пресс-конференции. Я импортировал TouchableOpacity в другой класс и хотел обработать там событие onPress. Но мой код не работает. С импортом тоже проблем нет. Вот мой класс, импортирующий компонент TouchableOpacity

import React, {Component} from 'react';
import {Text,View,Alert} from 'react-native';
import MyButton from './MyButton';

class FrontPage extends Component{
 OnPressNextButton=()=> {
   Alert.alert('You tapped the next button');
 }
 OnPressBackButton=()=> {
  Alert.alert('You tapped the back button');
}
  render(){
    return(
      <View style={styles.viewStyle}>
          <View >
            <MyButton  buttonText="Back" onPress={this.OnPressBackButton} />
            </View>
            <View style={styles.marginStyle}>
              <MyButton  buttonText="Next" onPress={this.OnPressNextButton} />
          </View>
        </View>
    );

  }
}const styles={
  viewStyle:{
    flexDirection:'row',
    borderWidth:1,
    borderBottomWidth:0,
    borderRadius:2,
    borderColor:'#ddd',
    shadowColor:'#000',
    shadowOffset:{width:0, height:2},
    shadowOpacity:0.2,
    marginLeft:5,
    marginRight:5,
    marginTop:5,
    elevation:1,
    position:'relative'
  },marginStyle:{
    marginLeft:128
  }
};
export default FrontPage;

и компонент TouchableOpacity создается как

import React,{Component} from 'react';
import {Text,View,TouchableOpacity} from 'react-native';
const MyButton=(props)=>{

  return(
    <TouchableOpacity style={styles.buttonStyle} >
      <Text style={styles.textStyle}>
        {props.buttonText}
      </Text>
    </TouchableOpacity>
  );
}
const styles={
  buttonStyle:{
    width:100,
    height:50,
    borderWidth:1,
    alignItems:'center',
    borderRadius:5,
    backgroundColor:'#fff',
    borderColor:'#007aff',
    shadowOpacity:0.8,
    marginLeft:5,
    marginRight:5,
    marginTop:455,
    position:'relative'
  },
  textStyle:{
    color:'#00f',
    borderColor:'#007aff',
    fontSize:20,
    paddingTop:10,
    paddingBottom:10,
    fontWeight:'600'
  }
};
export default MyButton;

person Mithun Adhikari    schedule 02.09.2017    source источник
comment
Где вы обработали onPress в своем компоненте? Ты не.   -  person Khalil Khalaf    schedule 02.09.2017
comment
Вот о чем я спрашиваю. Где и как мне обращаться с onPress?   -  person Mithun Adhikari    schedule 04.09.2017


Ответы (1)


Вы должны передать действие props to onPress в компоненте TouchableOpacity в этом коде. Я поместил обратный вызов onPress с тем же именем в компонент FrontPage, вы можете изменить имя обратного вызова onPress в этом компоненте на свое имя.

Это должно быть в вашем компоненте FrontPage

return(
  <View style={styles.viewStyle}>
      <View >
        <MyButton  buttonText="Back" onPress={this.OnPressBackButton} />
        </View>
        <View style={styles.marginStyle}>
          <MyButton  buttonText="Next" onPress={this.OnPressNextButton} />
      </View>
    </View>
);

это должен быть ваш компонент TouchableOpacity

const MyButton=({ onPress })=>{

  return(
    <TouchableOpacity style={styles.buttonStyle} onPress={onPress}>
      <Text style={styles.textStyle}>
        {props.buttonText}
      </Text>
    </TouchableOpacity>
  );
}
person Maulana Prambadi    schedule 02.09.2017
comment
Спасибо чувак. Я получил идею. Это должно было быть const MyButton=(props)=›{ return( ‹TouchableOpacity style={styles.buttonStyle} onPress={this.onPress}› ‹Text style={styles.textStyle}› {props.buttonText} ‹/Text › ‹/TouchableOpacity›); } - person Mithun Adhikari; 05.09.2017