繁体   English   中英

更改另一个组件中的状态

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM