在做项目的时候,可能会遇到这么一个需求:在一个列表里,复制某一个列表项的内容
这个时候,我们首先是需要拿到需要复制的数据,再使用第三方库 copy-to-clipboard
小试牛刀
新手(比如我),可能直接这么写:
import { createRef } from 'react'
export default function App() {
const itemsRef = createRef()
const data = [
{ type: 'type1', content: 'type1 content' },
{ type: 'type2', content: 'type2 content' }
]
return (
<div className='App'>
{data.map(item => (
<div>
<span>{item.type} - </span>
<span ref={itemsRef}>{item.content}</span>
<button onClick={() => console.log(itemsRef.current.innerText)}>current content</button>
</div>
))}
</div>
)
}
页面内容是这样的
但是无论点击哪一个 current content,react 只会获取的到最后的 content: type2 content
但是我不想这样啊!咋办?
想想:我是不是只用了一个 ref?我是不是应该使用多个 ref?那我使用 ref数组吧!
使用 ref 数组
import { useRef } from 'react'
export default function App() {
const itemsRef = useRef([])
const data = [
{ type: 'type1', content: 'type1 content' },
{ type: 'type2', content: 'type2 content' }
]
return (
<div className='App'>
{data.map((item, index) => (
<div>
<span>{item.type} - </span>
<span ref={el => (itemsRef.current[index] = el)}>{item.content}</span>
<button onClick={() => console.log(itemsRef.current[index].innerText)}>current content</button>
</div>
))}
</div>
)
}
最终输出:
ok,解决!