根据本地测试,行渲染函数中的“this”似乎为空。因此,这阻止我在 onPress 属性上绑定(bind)本地函数。
我有这个渲染 block :
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]
有人可以指出是什么原因造成的吗?谢谢。
最佳答案
this
为 null,因为 _renderRow
尚未绑定(bind)到当前类。请记住:
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
。您可以通过以下方式绑定(bind)它:
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
}
}
关于listview - 该值在函数(React-Native)中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29532926/