根据本地测试,“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
- }
- }