[英]Change state in another component
我正在嘗試獲取要在子組件中使用的變量heartIconColor
。 但是我遇到了錯誤。 如何獲得此變量作為圖標的顏色?
ReferenceError:找不到變量:heartIconColor
我的app.js
export default class Home extends Component {
constructor(props){
super(props);
this.state = {
liked: false
}
}
likePost = (author, id) => {
alert("Liked!!" + author + id)
this.liked()
}
liked(){
this.setState({
liked: !this.state.liked
})
}
renderItem = ({ item, index }) => {
return (
<Post
like={this.likePost}
liked={this.state.liked}
/>
)
}
render() {
const heartIconColor = this.state.liked ? "red" : null;
return (
<FlatList data={this.state.getData} renderItem={this.renderItem}>
</FlatList>
)
}
我的組件:
const Post = (props) => {
const styles = StyleSheet.create({
heartIcon: {
fontSize: 20,
color: heartIconColor,
}
})
return (
<View style={styles.flex}>
<Text><Icon onPress={() => onClick={this.props.like}} style={styles.heartIcon} type="Octicons" name="heart" /></Text>
</View>
)
}
export { Post };
您可以將圖標顏色設置為
const styles = StyleSheet.create({
heartIcon: {
fontSize: 20,
color: props.liked ? "red" : null,
}
})
只需將道具iconColor從State傳遞到Post組件:
renderItem = ({ item, index }) => {
const heartIconColor = this.state.liked ? "red" : null;
return (
<Post
like={this.likePost}
liked={this.state.liked}
iconColor={heartIconColor}
/>
)
}
因此,在Post組件中輸入以下內容:
heartIcon: {
fontSize: 20,
color: this.props.iconColor,
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.