我正在尝试获取要在子组件中使用的变量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 };
答案 0 :(得分:1)
您可以将图标颜色设置为
const styles = StyleSheet.create({
heartIcon: {
fontSize: 20,
color: props.liked ? "red" : null,
}
})
答案 1 :(得分:1)
只需将道具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,
}