如何将函数添加到动态创建的列表视图按钮中的本机?
我收到错误" undefined不是一个函数(评估' _this4.fun()')"
import React, { Component } from 'react';
import {
StyleSheet,
Text,
ListView,
View,
Alert,
ToolbarAndroid,
TouchableOpacity
} from 'react-native';
var _navigator;
export default class Quotes extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
fun(){
this.setState({
loaded: true
});
}
getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({dataSource:this.state.dataSource.cloneWithRows(responseJson.movies),
});
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
render () {
_navigator = this.props.navigator;
return (
<View style={styles.parentContainer}>
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={()=>this.getMoviesFromApiAsync()}>
<Text style={styles.buttonText}>testing network</Text>
</TouchableOpacity>
</View>
<Text style={styles.bigblue}>Dynamiclly created buttons below</Text>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}/>
</View>
)
}
在创建列表视图中动态创建的按钮后,我需要在单击时调用 fun()功能 我注意到 fun()只有在我创建动态创建的按钮时才会调用,如果我创建一个静态按钮,我可以正常调用它。
renderMovie(moviess) {
return (
<View style={styles.container}>
<View>
<TouchableOpacity
style={styles.button}
onPress={()=>this.fun()}>
<Text style={styles.buttonText}>{moviess.releaseYear}</Text>
</TouchableOpacity>
<Text>{moviess.releaseYear}</Text>
</View>
</View>
);
}
}
var styles = StyleSheet.create({
parentContainer: {
flex: 1,
},
container: {
justifyContent: 'center',
backgroundColor: '#F5FCFF',
flexDirection: 'row',
},
bigblue: {
color: 'grey',
fontWeight: 'bold',
fontSize: 20,
},
toolbar: {
height: 56,
backgroundColor: '#4883da',
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 70,
width: 70,
backgroundColor: '#FFC0CB',
alignSelf: 'center',
marginRight: 10,
marginLeft: 10,
marginTop: 10,
marginBottom: 15,
borderRadius: 50,
borderWidth: 0.7,
borderColor: '#d6d7da',
justifyContent: 'center'
}
});
我收到错误** undefined不是函数(评估&#39; _this4.fun()&#39;)**
答案 0 :(得分:3)
不知何故,你在this
内部失去renderMovie(moviess)
,因为它已经绑定到全局范围,而不再是类Quotes
。
如果您添加renderRow={this.renderMovie.bind(this)}
,它应该有效。 (而不是renderRow={this.renderMovie}
)
您还可以添加构造函数:this.renderMovie = this.renderMovie.bind(this);