React组件render方法中如何为map/数组的单个元素设置prop
实现方案
问题根源是当前使用单个布尔类型的全局状态控制所有列表项的提示显隐,所有项共享同一个状态自然会同步触发展示。我们可以把状态改为存储超限项的索引集合,单独标记每个位置的超限状态即可。
步骤1:补全FieldProps类型定义
fileLimitWarning直接定义为布尔类型即可:
interface FieldProps { fileLimitWarning?: boolean; handleFileSelection: (files: FileList | null) => void; }
步骤2:修改容器组件的状态定义
将原来的单个布尔状态改为数组,存储所有超限项的索引:
const ContainerOfDataField = () => { // 替换原来的fileLimitWarning状态 const [warningIndexes, setWarningIndexes] = useState<number[]>([]);
步骤3:改造文件选择处理函数
新增索引入参,用来标记当前操作的是哪个列表项:
// 入参新增当前项的index const handleFileSelection = (files: FileList | null, index: number) => { // 先移除当前索引的超限标记 setWarningIndexes(prev => prev.filter(item => item !== index)); const [currentFile] = files || []; // 注意:原代码的判断逻辑写反了,文件大小>250M才需要触发超限提示 if(currentFile?.size > 250000000) { setWarningIndexes(prev => [...prev, index]); } }
步骤4:修改列表渲染逻辑
给每个子组件传入对应的状态,绑定当前索引到处理函数:
return ( <ul> { fields?.map((promoField: Field, index: number) => { return ( <DataField key={index} // 仅当前索引在超限集合中时,传true fileLimitWarning={warningIndexes.includes(index)} // 给处理函数绑定当前项的索引 handleFileSelection={(files) => handleFileSelection(files, index)} /> ); }) } </ul> ) }
优化提示
如果你的fields数组后续会有新增/删除/排序操作,不要用index作为key,替换为每个promoField自带的唯一ID即可,避免状态错位。
内容的提问来源于stack exchange,提问作者Reacting
相关产品推荐
相关产品推荐

