【问题标题】:How to Change Icon name when pressed in react native vector icon按下反应原生矢量图标时如何更改图标名称
【发布时间】:2019-05-19 21:11:29
【问题描述】:

我正在使用 react-native-vector-icons

我想在第一次加载屏幕时更改图标的名称,我可以很好地看到图标,但是当按下它时它不再起作用并且我看到问号 ?

this.state={
favIcon:"heart-empty"
}
 <Icon name={`ios-${favIcon}`} style={{ backgroundColor: "red" }} size={30} color="#fff" onPress={() => this.setState({ favIcon: "heart" }, alert(favIcon))} />

任何想法来处理名称以接受变量?

当我登录 this.state.FavIcon 时,它是 undefined !!

--

没关系,它现在可以工作了:D,我只是在 setState 时编辑图标的名称,并重命名状态的名称

现在新的 Q 是 当我按下图标时,我将图标更改为“ios-heart”,现在如果我想再次按下,我想更改为“ios-heart-empty”

我想做的功能的想法是添加到收藏夹和从收藏夹中删除

【问题讨论】:

  • 您正在使用favIcon 设置状态并将状态用作FavIcon。能不能说的更清楚一点?
  • 有点迷惑,变量名是FavIcon还是favIcon?如果您设置 favIcon 并尝试记录 FavIcon,它将是未定义的
  • 是的,我就是这样做的,你能再检查一下问题吗

标签: javascript reactjs react-native redux react-native-vector-icons


【解决方案1】:

您可以执行以下操作:

constructor(props) {
   super(props)

   this.state={ 
      providerId: '',
      providerName: '',
      providerService: '',
      fav: false
   } 

   this.ref = firebase.database().ref(`favorites/${firebase.auth().currentUser.uid}`);
}
componentDidMount() {
    this._onFavourite = this.ref.on('child_added', () => {
        this.setState({
            fav: true
        }, alert("Added To Favorite List"))
    })
    this._onUnFavourite = this.ref.on('child_removed', () => {
        this.setState({
            fav: false
        }, alert("Removed from Favorite List"))
    })
}
componentWillUnmount() {
    if (this._onFavourite) {
        this.ref.off('child_added', this._onFavourite);
    }
    if (this._onUnFavourite) {
        this.ref.off('child_removed', this._onUnFavourite);
    }
}
_favOrUnFav = () => {
    if (!this.state.fav){ 
        const { 
            providerId,
            providerName,
            providerService
        } = this.state;

        this.ref.set({
            providerId,
            providerName,
            providerService
        })
    } else ref.set(null)  OR you can use ref.remove()
}
const {
     fav
} = this.state

<Icon 
    name={`ios-heart${fav ? "" : "-empty"}`}
    style={{ backgroundColor: "red" }} 
    size={30} 
    color="#fff" 
    onPress={this._favOrUnFav} 
/>

希望对你有帮助。

【讨论】:

  • 非常感谢,它工作得很好,但是当我进入用户配置文件时我有一些小问题我想看到收藏图标它是“ios-heart”,这意味着它在最喜欢的列表,但是当我转到用户个人资料时,我只看到“ios-heart-empty”,但顺便说一下,用户已经在最喜欢的列表中,如何处理这些
【解决方案2】:

onPress 仅适用于 Icon.Button,不适用于 Icon。有关Icon.Button 的更多信息,请参阅https://github.com/oblador/react-native-vector-icons#iconbutton-component

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    相关资源
    最近更新 更多