伪代码
category.map(item=>{
return (<Category onClick={()=>{this.categorySelected(item)}} />)
})
1
mxT52CRuqR6o5 327 天前
category.map(item=>{
return (<Category categorySelected={this.categorySelected} />) }) |
![]() |
2
TomVista OP @mxT52CRuqR6o5 非组件,例如 div,这种有什么办法? 或者说这个情况,拆分成组件,比较合适?
|
![]() |
3
yimity 327 天前 ![]() 把 ()=>{this.categorySelected(item)} 这个顶一个 useCallback 包起来的函数试试。
|
![]() |
4
yimity 327 天前
顶一个 -> 定一个
|
5
mxT52CRuqR6o5 327 天前 ![]() @TomVista 其实大部分时候不差这点性能,你要是在意就在合适的边界处抽象出组件
|
![]() |
6
h1104350235 327 天前 ![]() useCallback()试试,搜下 react 性能优化
|
![]() |
7
zhea55 327 天前
import React from 'react'
import PropTypes from 'prop-types' export default class Category extends React.Component { static propTypes = { item: PropTypes.object.isRequired, } constructor(props) { super(props); this.onCategoryClick = this.onCategoryClick.bind(this) } onCategoryClick() { this.props.onClick(this.props.item); } render() { return ( <div onClick={this.onCategoryClick}> </div> ) } } |
![]() |
8
zhea55 327 天前
```Javascript
import React from 'react' import PropTypes from 'prop-types' export default class Category extends React.Component { static propTypes = { item: PropTypes.object.isRequired, } constructor(props) { super(props); this.onCategoryClick = this.onCategoryClick.bind(this) } onCategoryClick() { this.props.onClick(this.props.item); } render() { return ( <div onClick={this.onCategoryClick}> </div> ) } } ``` |
9
FaiChou 327 天前
加一个 key ? <Category key={item.id.toString()} ... />
|
10
xd199153 327 天前
因为参数变化才需要重新定义,那利用一下 event 对象吧。
const handleClick= (e)=>{ const item = category.find(x=>x.id ===e.target.dataset.id); } category.map(item=>{ return (<div data-id={item.id} onClick={handleClick} />) }) |
11
xd199153 327 天前 ![]() 不过直觉上这种性能没多大差别吧,写法麻烦了。你可以先测试一下看看。
|
![]() |
12
zhea55 327 天前 ![]() |
![]() |
13
muzuiget 326 天前
关键词:事件委托,把数组索引存到 dom 上,然后在父组件响应事件,使用 event.target 取的产生事件对象 dom,获取数组索引。
<div onClick={this.categorySelected}> {category.map((item, i)=>{ return (<Category index={i} />), }) </div> |
![]() |
15
dany813 326 天前
你这箭头函数。。。每次都是一个新的引用
|
![]() |
17
TomVista OP @yimity 是事件委托,但是循环这种情况 虽然都是 onClick=myFunction,myFunction==myFunction //true,最后到 docment 上会有循环长度数量的事件委托,
如果扔到 循环的父元素上,会只有一个 onClick=myFunction |