2017-09-02 51 views
0

我想要做的是創建一個TouchableOpacity一次,並在我的程序中的任何地方使用它。我在處理新聞事件時反駁了一個問題。我在其他課程中導入了TouchableOpacity,並希望在那裏處理onPress活動。但是我的代碼不工作。導入也沒有問題。 這裏是我的課堂導入TouchableOpacity組件反應本機TouchableOpacity onPress事件不工作從其他職業打電話

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; 
+0

你在哪裏處理'onPress'在你的組件?你沒有。 –

+0

這就是我所要求的。我在哪裏以及如何處理onPress? –

回答

1

創建你應該通過propsonPress行動在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> 
); 
} 
+0

謝謝你。我明白了。它應該是 常量爲myButton =(道具)=> { 回報( <文本樣式= {styles.textStyle}> {道具.buttonText} ); } –

+0

好吧,如果它現在工作 –