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

前端之家收集整理的这篇文章主要介绍了listview – 该值在函数中为null(React-Native)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
根据本地测试,“render”函数中的“this”似乎为空。因此,这样可以防止在onPress支路上绑定本地功能

我有这个渲染块:

  1. render() {
  2. return (
  3. <ListView
  4. dataSource={this.state.dataSource}
  5. renderRow={this._renderRow}
  6. renderHeader={this._renderHeader}
  7. style={styles.listView} />
  8. );
  9. }

和本地功能

  1. _visitEntryDetail() {
  2. console.log('test');
  3. }

然后行渲染

  1. _renderRow(something) {
  2. return (
  3. <TouchableHighlight
  4. style={[styles.textContainer,filestyle.container]}
  5. onPress={this._visitEntryDetail.bind(this)} >
  6. <View>
  7. <Text style={filestyle.text1} >{something.detail}</Text>
  8. <Text style={filestyle.text2} >{something.size},{something.timestamp}</Text>
  9. </View>
  10. </TouchableHighlight>
  11. );
  12. }

这返回

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

在renderRow上检查“this”在以下替换代码时返回null:

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

具有以下控制台输出

  1. RCTJSLog> null

但是很好

  1. render() {
  2. console.log('inside render. this value is below me');
  3. console.log(this);
  4. return (
  5. <ListView

安慰

  1. RCTJSLog> "inside render. this value is below me"
  2. 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。你可以绑定它:

  1. class SomeComponent extends Component {
  2.  
  3. constructor(props) {
  4. super(props)
  5.  
  6. //binding function
  7. this.renderRow = this.renderRow.bind(this)
  8. this.callThisFunction = this.callThisFunction.bind(this)
  9. }
  10.  
  11. renderRow() {
  12. console.log(this) //not null now
  13. return (
  14. <View>
  15. <TouchableHighlight onPress={this.callThisFunction}>
  16. <Image source={require('image!prev')}/>
  17. </TouchableHighlight>
  18. </View>
  19. )
  20. }
  21.  
  22. callThisFunction() {
  23. console.log(this) //not null now
  24. }
  25. }

猜你在找的React相关文章