2016-04-26 105 views
2

我似乎被卡在按鈕按下時調用函數。無論我嘗試什麼方法,我都會得到不同的未定義錯誤。React-Native ListView onPress - undefined不是對象

我正在運行反應原生0.24,目前只爲Android設備編碼。

請參閱下面的代碼:

class ListPage extends Component { 

    constructor(props){ 
    super(props); 
     this.nav = props.nav; 
     this.route = props.route; 
     this.ds = new ListView.DataSource({ 
      rowHasChanged: (row1, row2) => row1 !== row2, 
     }); 
     this.state = ({ 
      visible: false, 
      dataSource: this.ds.cloneWithRows(props.fullList), 
     }); 
    } 

    goToPage(name){ 
     this.nav.push({ name: name }); 
    } 

    loadModal() { 
     this.setState({ visible: true }); 
    } 

    list(row){ 
     return (
      <View style={styles.box}> 
        <TouchableNativeFeedback underlayColor="#FFF" 
        onPress={this.goToPage.bind(this,'ShowRow')}> 
         <View> 
          ...ShowRow Button 
         </View> 
        </TouchableNativeFeedback> 
        <TouchableNativeFeedback 
         onPress={this.loadModal.bind(this)} > 
         <View style={styles.button}> 
          ...Modal Button 
         </View> 
        </TouchableNativeFeedback> 
       </View> 
     ); 
    } 

    render(){ 
     return (
      <View style={styles.container}> 
       <Modal visible={this.state.visible} 
        onRequestClose={() => {this.setState({visible: false}) }} > 
        <View> 
         <Text>I am a Modal!</Text> 
        </View> 
       </Modal> 
       <ListView 
        dataSource={this.state.dataSource} 
        renderRow={this.list} /> 
      </View> 
     ); 
    } 
} 

每當我按下其中一個按鈕我得到了一個未定義不是都this.goToPage.bind和this.loadModal.bind對象錯誤。

如果我試試這個:

render() { //or inside list(row) function 
    goToPage = function(name){ 
     this.nav.push etc etc 
    } 
    loadModal = function() { setState etc... } 
    return (
     ...render stuff 
    ) 
} 

現在說不確定是不是都this.nav和this.setState

的對象,但如果我這樣做:

constructor() { 
    ... 
    goToPage = function(name){ 
     props.nav.push(...); 
    } 
} 

它的工作原理.....但我知道這是不正確的方法,我也無法setState的模態。爲什麼它不與第一種方法一起工作?非常感謝。

回答

10

好的,找到了解決辦法。在renderRow中,我需要像這樣綁定函數:

<ListView dataSource={this.state.dataSource} 
renderRow={this.list.bind(this)} /> 

現在我可以用第一種方法調用函數。

相關問題