this value is null in function (React-Native)

时光怂恿深爱的人放手 提交于 2019-11-28 09:02:45
NightFury

this is null because _renderRow has not been binded to the current class. Please keep in mind:

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.

This statement applies to any function being passed to the component. For example, you want to call a function callThisFunction on pressing TouchableHighlight. You can bind it by:

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

An alternative to NightFury's solution would be to use ES6 Arrow Function syntax without having to manually bind the function in the constructor. Your render() would then look like this:

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

If you want to pass function to a 3rd party component always pass functions like that:

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

When you bind function like that, it didnt lose function instance in other classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!