出错的伪代码如下:
import { Input } from 'antd'...let arr = [1, 2, 3, 4]...return (<div>{arr.map((item) => {return ( <Inputkey={Math.random()}onChange={(value)=>{console.log(value)}}/>)})}</div>)
看似普通,暗含杀机
我有时会使用Math.random()去当作key值,但是更新渲染时,每一次更新都会重新计算key值,这就意味这我们的Input已经不是同一个了,自然就会失去焦点。
最好的办法就是使用对象的id,index也要慎用