【问题标题】:Material-ui & TouchTap: Getting key of ListItemMaterial-ui & TouchTap:获取 ListItem 的键
【发布时间】:2015-09-08 12:10:03
【问题描述】:

我有一个使用 material-ui 的项目列表。我想在单击项目时调用 _handleTouchTap() 并将 ListItem 的键传递给处理程序。

添加

onTouchTap={this._handleTouchTap}

to 不起作用,因为“this”似乎是错误的范围

var React = require('react');
var Mui = require('material-ui');
var ThemeManager = new Mui.Styles.ThemeManager();
ThemeManager.setTheme(ThemeManager.types.LIGHT);
var injectTapEventPlugin = require('react-tap-event-plugin');
injectTapEventPlugin();
var List = Mui.List
var ListItem = Mui.ListItem

var Main = React.createClass({
  childContextTypes: {
    muiTheme: React.PropTypes.object
  },
  getChildContext: function () {
    return {
      muiTheme: ThemeManager.getCurrentTheme()
    }
  },
  render: function() {
    var items = [
      {id: 1, title: 'Item 1'},
      {id: 2, title: 'Item 2'},
      {id: 3, title: 'Item 3'}
    ]
    return (
        <List>
          {items.map(function(item){
            return <ListItem key={item.id} primaryText={item.title} />
          })}
        </List>
    )
  },

  _handleTouchTap: function() {
    // the key of the item should be passed though here
  }
});

React.render(<Main />, document.body);

【问题讨论】:

  • 在事件处理程序中使用 id 而不是 key。只需将 id={item.id} 添加到您的 ListItem。然后 event.target.id 返回 id。

标签: reactjs material-ui


【解决方案1】:

如果 event.target.id 由于 Tim Welch 上面指出的问题而无法正常工作,您可以简单地将项目 ID 作为参数传递给您的处理函数

render: function() {
        var items = [
          {id: 1, title: 'Item 1'},
          {id: 2, title: 'Item 2'},
          {id: 3, title: 'Item 3'}
        ]
        return (
            <List>
              {items.map(function(item){
                return <ListItem key={item.id} 
                                 primaryText={item.title} 
                                 onTouchTap={this._handleTouchTap.bind(this, item.id)}/>
              })}
            </List>
        )
      },

      _handleTouchTap: function(id) {
        console.log(id) // Logs item id
      }
});

不要使用onTouchTap={this._handleTouchTap.bind(this, item.id)},如果你使用的是es6,你可以使用es6的胖箭头函数,它会自动为你绑定this。可以这样做: onTouchTap={() =&gt; this._handleTouchTap(item.id)}

【讨论】:

  • 对我不起作用... _handleTouchTap 直接为项目的每个元素执行。
  • @Sucrenoir 检查我上面编辑的答案。确保您使用 bind() 绑定 this 或使用 es6 粗箭头函数(如果您使用的是 es6)。
  • 它可以工作,但只能使用 onClick :-) 不是很容易阅读...非常感谢
【解决方案2】:

分享我学到的东西。看看 Material-UI 提供的 MakeSelectable 高阶组件,用于创建一个可选列表,该列表为您提供当前选定项 onChange 的索引。自从提出问题以来,这可能是新的。注意下面 ListItem 的 value 属性和 SelectableList 上的 onChange 事件。

import {List, ListItem, MakeSelectable} from 'material-ui/List'
SelectableList = MakeSelectable(List)

const siteItems = Object.keys(sites || {}).map((index) => {
  const site = sites[index]
  return (<ListItem
    key={index + 1}
    value={site.id}
    leftAvatar={<Avatar icon={<PinDrop />} />}
    primaryText={site.name}
    secondaryText={site.description}
    style={styles.list}
  />)
})
CurList = (
  <div style={styles.listcontainer}>
    <SelectableList onChange={this.siteSelected}>
      {siteItems}
    </SelectableList>
  </div>
)

我在设置列表项的 id 并尝试通过 event.target.id 访问它的模式中发现的问题是,如果您的列表项中有子元素(如图标、标签等), event.target 会有所不同. 大多数 List 示例都有。

【讨论】:

  • 将 id 设置为 value 道具对我有用。谢谢蒂姆。
【解决方案3】:

如果您想使用较新的 ES6 类语法和箭头函数,这可能是答案。如果您使用类语法正确指定this 上下文,则需要显式绑定this 关键字。 onTouchTap 需要一个方法,所以我使用 ES6 箭头函数返回一个函数。

import { Component, React } from 'react';
import { List, ListItem } from 'material-ui/List';
class Main extends Component {

   constructor() {
      super(...arguments);
      this._handleTouchTap = this._handleTouchTap.bind(this);
   }

   _handleTouchTap(id) {
       return () => console.log(id) // Logs item id
   }

   render () {        
      var items = [
         {id: 1, title: 'Item 1'},
         {id: 2, title: 'Item 2'},
         {id: 3, title: 'Item 3'}
       ];

       return (
           <List>
             {items.map(function(item){
               return (
                  <ListItem 
                     key={item.id} 
                     primaryText={item.title} 
                     onTouchTap={this._handleTouchTap(item.id)}
                   />
                )
             })}
           </List>
       );
    }
}

【讨论】:

  • 您可以通过简单地执行onTouchTap={() =&gt; this._handleTouchTap(item.id)} 来实现相同的绑定,而无需在构造函数中显式绑定this
【解决方案4】:

您必须设置 listitem onTouchTap 属性并将事件设置为 handleTouchTap 参数

<ListItem onTouchTap={this._handleTouchTap} />

_handleTouchTap: function(event){
  var clickedID = event.target.id
}

【讨论】:

  • 对我不起作用。 id 似乎没有在 v0.15.0 beta 2 中设置。
猜你喜欢
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多