函数中该值为null(React-Native)

时间:2015-04-09 07:57:08

标签: listview this react-native

根据本地测试,'这个'在行渲染函数中似乎是null。因此,这阻止了我在onPress prop上绑定本地函数。

我有这个渲染块:

render() {
    return (
        <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow}
            renderHeader={this._renderHeader} 
            style={styles.listView} />
    );
}

和一个本地函数

_visitEntryDetail() {
    console.log('test');
}

然后行渲染

_renderRow(something) {
    return (
        <TouchableHighlight
            style={[styles.textContainer, filestyle.container]} 
            onPress={this._visitEntryDetail.bind(this)} >
            <View>
                <Text style={filestyle.text1} >{something.detail}</Text>
                <Text style={filestyle.text2} >{something.size}, {something.timestamp}</Text>
            </View>
        </TouchableHighlight>
    );
}

返回

message: null is not an object (evaluating 'this.$FileList_visitEntryDetail')"

检查&#34;这&#34;当使用以下代码替换上面的代码时,renderRow返回null;

_renderRow(file) {
    console.log(this);
    return (
        <TouchableHighlight
            style={[styles.textContainer, filestyle.filelistcontainer]} 
             >

以下控制台输出:

RCTJSLog> null

时没事
render() {
    console.log('inside render. this value is below me');
    console.log(this);
    return (
        <ListView

控制台

RCTJSLog> "inside render. this value is below me"
RCTJSLog> [object Object]

有人可以指出造成这种情况的原因。感谢。

3 个答案:

答案 0 :(得分:47)

this为空,因为_renderRow尚未绑定到当前类。请记住:

  

在构造函数中,如果要将函数传递给任何反应组件,则需要显式绑定函数,因为有时它不会隐式绑定。

此语句适用于传递给组件的任何函数。例如,您想在按callThisFunction时调用函数TouchableHighlight。您可以通过以下方式绑定它:

class SomeComponent extends Component {

  constructor(props) {
    super(props)

    //binding function
    this.renderRow = this.renderRow.bind(this)
    this.callThisFunction = this.callThisFunction.bind(this)
  }

  renderRow() {
    console.log(this) //not null now
    return (
      <View>
        <TouchableHighlight onPress={this.callThisFunction}>
          <Image source={require('image!prev')}/>
        </TouchableHighlight>
      </View>
    )
  }

  callThisFunction() {
    console.log(this) //not null now
  }
}

答案 1 :(得分:3)

NightFury解决方案的替代方法是使用ES6 Arrow Function语法,而无需在构造函数中手动绑定该函数。您的render()将如下所示:

render() {
    return (
       <ListView
           dataSource={this.state.dataSource}
           renderRow={() => this._renderRow()}
           renderHeader={() => this._renderHeader()} 
           style={styles.listView} />
    );
}

答案 2 :(得分:0)

如果要将功能传递给第三方组件,请始终传递以下功能:

        <Carousel
          renderItem={item => this._renderItem(item)}
        />

当你绑定这样的函数时,它并没有丢失其他类中的函数实例