2016-07-19 50 views
1

我有一個LisView在我的組件如下執行功能:嘗試在ListView的行

class Test extends Component { 

    constructor(props) { 
    super(props); 

    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); 
    this.state = { 
     dataSource: ds.cloneWithRows(this.props.dataSource), 
    }; 
    } 

    componentWillReceiveProps(nextProps) { 
    if (this.props.dataSource !== nextProps.dataSource) { 
     this.setState({ 
     dataSource: this.state.dataSource.cloneWithRows(nextProps.dataSource), 
     }); 
    } 
    } 

    onPressRow(key) { 
    console.log(key); 
    } 

    getListView() { 
    if (this.props.isLoading) { 
     return (
     <ActivityIndicator 
      animating 
      size={'small'} 
      style={styles.spinner} 
      color={this.props.activityIndicatorColor} 
     /> 
    ); 
    } 
    return (
     <ListView 
     style={styles.listView} 
     keyboardShouldPersistTaps 
     keyboardDismissMode="on-drag" 
     enableEmptySections 
     dataSource={this.state.dataSource} 
     renderRow={this.renderRow} 
     automaticallyAdjustContentInsets={false} 
     /> 
    ); 
    } 

    renderRow(rowData) { 
    return (
     <View 
     style={styles.listButton} 
     > 
     <TouchableHighlight 
      style={styles.button} 
      onPress={() => this.onPressRow(rowData)} 
     > 
      <Text> 
      {rowData.description} 
      </Text> 
     </TouchableHighlight> 
     </View> 
    ); 
    } 

    render() { 
    return (
     <View> 
     <View> 
      // TEXTINPUT 
     </View> 
     {this.getListView()} 
     </View> 
    ); 
    } 
} 

export default Test; 

當我點擊一排,我想執行一個功能,但我有此錯誤:

_this2.onPressRow is not a function

爲什麼我不能讀取功能?我必須通過它作爲道具?

+0

綁定你的'renderRow',就像'renderRow = {this.renderRow.bind(this)}' – Cherniv

+0

謝謝@Cherniv – SaroVin

回答

0

如果您使用React.createClass,所有呼叫都會自動綁定,但使用extends React.Component的ES6方法時,必須綁定所有功能。

你可以做到這一點使用

renderRow={this.renderRow.bind(this)} 

或者是內聯的,你可以添加到您的構造函數,super()後:

this.renderRow = this.renderRow.bind(this); 

個人而言,我喜歡這種方法,因爲我覺得這個代碼更容易一點讀書。

有關ES6方式的更多信息,請查詢this link