【问题标题】:React JS - Event Handler in a dynamic listReact JS - 动态列表中的事件处理程序
【发布时间】:2017-08-31 15:40:10
【问题描述】:

我带来了一个基于动态列表的 API 内容,并且我试图在每个 li 上应用一个 mouserEnter。该事件通过切换每个列表项中的内容来产生。该事件正在运行,但它会同时切换所有列表项中的内容,但我希望它仅切换与接收 mouseEnter 的列表项匹配的内容。

import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class Dribbble extends React.Component {
  constructor(props) {
    super(props);    
   
    this.state = { 
      work: [],  
      hover: false      
    }; 
    
    this.handleMouseEnter = this.handleMouseEnter.bind(this);
    this.handleMouseLeave = this.handleMouseLeave.bind(this);
    
  }  

  handleMouseEnter(){
    this.setState({ hover: true })
  }

  handleMouseLeave(){
    this.setState({ hover: false })
  }

  componentDidMount() {
    this.ShotList();
  }

  ShotList() {
    return $.getJSON('https://api.dribbble.com/v1/shots?per_page=3&access_token=41ff524ebca5e8d0bf5d6f9f2c611c1b0d224a1975ce37579326872c1e7900b4&callback=?')
      .then((resp) => {
        this.setState({ work: resp.data.reverse() });
      });
  } 

  render() {  
    
    const works = this.state.work.map((val, i) => {    
     
     return <li key={i} className="box"          
          onMouseEnter={this.handleMouseEnter}
          onMouseLeave={this.handleMouseLeave}        
          >    
          {!this.state.hover ?     
            <div>
              <img className="cover" src={val.images.normal} />
              <div className="bar">
                <h2>{val.title}</h2>
                <span>{val.views_count}</span>
                <i className="fa fa-eye fa-2x" aria-hidden="true"></i>
              </div>
            </div> 
          : null} 
          {this.state.hover ?
            <div>
              <h3>{val.user.name}</h3>
              <img className="avatar img-circle" src={val.user.avatar_url}/>
              <p>{val.description}</p>              
            </div>
           :
           null
          }           
        </li>  
    });    

    return <ul>{works}</ul>
  }
}

这是我的代码:

【问题讨论】:

    标签: reactjs dictionary this eventhandler


    【解决方案1】:

    您的示例中有几个问题,首先正如@aherriot 所说,您应该将ul 移到地图之外。

    接下来我会将this.state.hover 设置为itemid 悬停在onMouseEnter 上。

    下面的 sn-p 显示了这个工作的一个基本示例,它应该很容易适应您的代码。

    class App extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          items: [{id: 1, name: 'Fred'}, {id: 2, name: 'Albert'}, {id: 3, name: 'Jane'}],
          hover: false,
        }
        
        this.handleMouseEnter = this.handleMouseEnter.bind(this);
        this.handleMouseLeave = this.handleMouseLeave.bind(this);
        this.renderItem = this.renderItem.bind(this);
      }
      
      handleMouseEnter(id){
        console.log(`handleMouseEnter this.setState({ hover: ${id} })`);
        this.setState({ hover: id })
      }
    
      handleMouseLeave(){
        console.log('handleMouseLeave this.setState({ hover: false })');
        this.setState({ hover: false })
      }
      
      renderItem(item, index) {
        let content = [];
        content.push(
          <span>ID: {item.id}, Name: {item.name}</span>
        );
        
        if(this.state.hover === item.id) {
          console.log('display " - hovering" for item id: ' + item.id);
          content.push(
            <span> - hovering</span>
          );
        }
        
        return (
          <li key={item.id}
            onMouseEnter={() => this.handleMouseEnter(item.id)}
            onMouseLeave={this.handleMouseLeave}
          >
            {content}
          </li>
        )
      }
      
      render() {
        return <ul>
            {this.state.items.map(this.renderItem)}
        </ul>
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
    <div id="root"></div>

    【讨论】:

    • 谢谢,但你能更好地解释一下吗?你的例子和我的有点不同。请给我更多的线索。
    • 我是 React JS 的初学者
    • 不同之处在于@Purgatory 不只是跟踪某物是否被悬停,它们正在跟踪被悬停的特定“工作”的ID。这样,当您在数组上进行映射时,您会检查每个数组的 id 是否与悬停的 id 匹配,并据此决定要渲染的内容。
    • @claudiobitar 我添加了一些console.log,这样您就可以看到发生了什么事情。不幸的是,我不确定如何才能更清楚地说明这一点。
    • 我在哪里输入这个值:'this.state.hover'?以及如何将其附加到 id 上?我是 React 的初学者。
    【解决方案2】:

    也许您应该将&lt;ul&gt; 标签移到this.state.work.map 之外,您只希望显示一个&lt;ul&gt;,而不是每个元素一个。

    您可以将其放在 div 标签内的底部:return (&lt;div&gt;&lt;ul&gt;{works}&lt;/ul&gt;&lt;/div&gt;)

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 2021-06-27
      • 1970-01-01
      • 2018-01-25
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      相关资源
      最近更新 更多