【问题标题】:React FontAwesome Icon not passing props for onClickReact FontAwesome Icon 没有为 onClick 传递道具
【发布时间】:2019-06-09 00:26:17
【问题描述】:

我有一个 React Web 应用程序,我已经安装并导入了 FontAwesome 图标库。

https://github.com/FortAwesome/react-fontawesome

 import { library } from '@fortawesome/fontawesome-svg-core';
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
 import { faIgloo } from '@fortawesome/free-solid-svg-icons';
 import { faStar } from '@fortawesome/free-solid-svg-icons';

 library.add(faStar);

调用 onClick 时,我无法从对象中获取道具。

看起来当我点击图标时我触发了我的反应按钮并且道具被很好地传递了。如果我直接点击图标,会触发 onClick 但不会传递道具。

<button  key={item.title} value={item.title} onClick={this.updateFavourites}>
<FontAwesomeIcon size="3x" icon="star" />                                
</button>


updateFavourites = event => {

    console.log("IN UPDATE FAVOURITES" + event.target.value);
    this.setState({
        selectedFavourite: event.target.value    
      });


      if (this.state.favourites.includes(event.target.value)){
        // Find and remove item from an array
        var i = this.state.favourites.indexOf(event.target.value);
        if(i !== -1) {
            this.state.favourites.splice(i, 1);
        }  
      }
      else{
        this.state.favourites.push(event.target.value);   
      }
}

我做错了什么?我已经阅读了我能找到的与此问题相关的所有帖子。

感谢您的帮助

【问题讨论】:

    标签: javascript reactjs onclick font-awesome


    【解决方案1】:

    我通过将值作为参数传递给 updateFavourites 函数来解决我的问题,而不是尝试通过道具从对象中获取值。

    变化如下。

    更新收藏功能:

     updateFavourites = event => {
    
        console.log("IN UPDATE FAVOURITES" + event);
        this.setState({
            selectedFavourite: event 
          });
    
    
          if (this.state.favourites.includes(event)){
            // Find and remove item from an array
            var i = this.state.favourites.indexOf(event);
            if(i !== -1) {
                this.state.favourites.splice(i, 1);
            }  
          }
          else{
            this.state.favourites.push(event);   
          }
    }
    

    按钮/图标:

     <button  key={item.title} value={item.title} onClick={() => this.updateFavourites(item.title)}>
     <FontAwesomeIcon size="3x" icon="star" />                                
     </button>
    

    【讨论】:

      【解决方案2】:

      因为&lt;FontAwesomeIcon size="3x" icon="star" /&gt; 没有任何价值。请记住,您在 updateFavourites 方法中使用 event.target.value,当您直接点击它时,图标将是“目标”。

      【讨论】:

      • 感谢您的评论。我现在明白我试图从图标中获取道具,它没有与按钮相同的道具。
      • 如果这对您有帮助,欢迎您接受我的回答。 :)
      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 2020-01-09
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多