我想显示带有来自 JSON 文件的新闻的卡片。获取 JSON 工作正常,但我想添加一个 onPress 事件,这样我就可以单击卡片并导航到文章。
我的卡片视图:
<Card>
<CardItem button onPress={this._OnButtonPress(news.id)}>
<Left>
<Body>
<Text style={styles.cardText}>{news.title}</Text>
</Body>
</Left>
</CardItem>
<CardItem>
<Left>
<Icon style={styles.icon} name="chatbubbles" />
<Text>{news.comments} comments</Text>
</Left>
<Right>
<Text>{news.published}</Text>
</Right>
</CardItem>
</Card>
我正在尝试将变量传递给 onButtonPress() 函数
_OnButtonPress(newsID) {
Alert.alert(newsID.toString());
}
为了测试 onPress 事件,我所做的只是提醒参数。
有谁知道我该如何解决这个问题以及我在这里做错了什么。提前致谢。
更新
我更新的课程:
import React, { Component } from "react";
import {
Image,
ListView,
StyleSheet,
Text,
View,
Alert
} from 'react-native';
import {
Container,
Header,
Left,
Right,
Button,
Card,
CardItem,
Icon,
Body,
Content,
Logo
} from 'native-base';
import styles from "./styles";
const logo = require("../../../img/f1today.png");
var REQUEST_URL = 'http://v2.first-place.nl/test/news.json';
class News extends Component {
constructor(props) {
super(props);
this._OnButtonPress = this._OnButtonPress.bind(this);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
_OnButtonPress(newsID) {
Alert.alert(newsID.toString());
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.articles),
loaded: true,
});
})
.done();
}
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<Container style={styles.container}>
<Header
style={{ backgroundColor: "#fff" }}
androidStatusBarColor="#f05423"
iosBarStyle="light-content">
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("DrawerOpen")}
>
<Icon name="ios-menu" style={{color: 'black'}} />
</Button>
</Left>
<Body>
<Image source={logo} style={styles.headerLogo} />
</Body>
<Right />
</Header>
<Content padder>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderNews}
style={styles.listView}
/>
</Content>
</Container>
);
}
renderLoadingView() {
return (
<View style={styles.loading}>
<Text>
Loading news...
</Text>
</View>
);
}
renderNews(news) {
return (
<Card>
<CardItem button onPress={()=> this._OnButtonPress(news.id)}>
<Left>
<Body>
<Text style={styles.cardText}>{news.title}</Text>
</Body>
</Left>
</CardItem>
<CardItem>
<Left>
<Icon style={styles.icon} name="chatbubbles" />
<Text>{news.comments} comments</Text>
</Left>
<Right>
<Text>{news.published}</Text>
</Right>
</CardItem>
</Card>
);
}
}
export default News;
原文由 abbob1 发布,翻译遵循 CC BY-SA 4.0 许可协议
您遇到的问题是该方法无法访问视图的范围。现在你的 renderNews 方法是这样定义的:
如果您以这种方式声明您的方法,您将无法在您的方法上使用 this,并且由于“this”未定义,所有方法都将触发错误,因为您正在尝试访问“undefined.methodName()”。话虽如此,您应该将上下文“绑定”到以这种方式声明它的方法:
现在您已将上下文附加到该方法,并且“this”在内部是可访问的。