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

bor*_*mes 20 listview this react-native

根据本地测试,'this'在行渲染函数中似乎为null.因此,这阻止了我在onPress道具上绑定本地函数.

我有这个渲染块:

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

和一个本地功能

_visitEntryDetail() {
    console.log('test');
}
Run Code Online (Sandbox Code Playgroud)

然后行渲染

_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>
    );
}
Run Code Online (Sandbox Code Playgroud)

这回来了

message: null is not an object (evaluating 'this.$FileList_visitEntryDetail')"
Run Code Online (Sandbox Code Playgroud)

检查renderRow上的"this"在替换上面的代码时返回null:

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

以下控制台输出:

RCTJSLog> null
Run Code Online (Sandbox Code Playgroud)

但是很好

render() {
    console.log('inside render. this value is below me');
    console.log(this);
    return (
        <ListView
Run Code Online (Sandbox Code Playgroud)

安慰

RCTJSLog> "inside render. this value is below me"
RCTJSLog> [object Object]
Run Code Online (Sandbox Code Playgroud)

有人可以指出导致这种情况的原因.谢谢.

Nig*_*ury 47

this为null,因为_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
  }
}
Run Code Online (Sandbox Code Playgroud)