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

根据本地测试,“render”函数中的“this”似乎为空。因此,这样可以防止在onPress支路上绑定本地功能

我有这个渲染块:

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')"

在renderRow上检查“this”在以下替换代码时返回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]

有人可以指出是什么原因造成的。谢谢。

这是null,因为_renderRow尚未绑定到当前类。请记住:

In constructor,you need to explicitly bind a function,if you want to pass it to any react component,as sometimes it doesn’t bind implicitly.

此声明适用于传递给组件的任何函数。例如,您想要按TouchableHighlight调用一个函数callThisFunction。你可以绑定它:

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
  }
}

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...