如何在为组件设置 ref 时传递道具


this.map[col1][row1] = <MemoizedItem key={item} x={row1} y={col1} />
this.setState({ map: this.map })

这是我的代码,我把所有项目都放在参数图中。 并使用以下内容进行渲染:

renderItem() {
return this.state.map.map((row) => {
return row.map((item) => {
return item;
})
})
}

现在,我正在尝试通过this.state.map[0][0].props.color ='#fff'传递项目中的道具颜色,但不起作用,收到错误"无法添加属性颜色,对象不可扩展",那么有什么办法可以做到这一点吗?

不应将组件存储在组件状态 您可以将数据存储在这样的状态

let data = [{id:'row1', cols:[{id:'col1'}, {id:'col2'}]} , {...}, ...]
this.setState({
map: data
})

并使用记忆组件进行渲染

renderItem() {
return this.state.map.map((row, rowIndex) => {
return row.cols.map((item,index) => {
//you can pass whatever you want to pass to the component
return <MemoizedComponent key={rowIndex+index} x={item} y={row} yourprops={condition ? color1: color2} />
})
})
}

最后,您可以通过设置状态来更新数据


let final = this.state.data.map(r => {
if (r === 'your condition') {
return Object.assign({}, r, {
cols: r.cols.map(c => {
if (c === 'your col condition') {
return Object.assign({}, c, {
changedProp: 'changedPropvalue',
});
} else {
return c;
}
}),
});
}else{
return r
}
});
...
this.setState({data:final})

因此,当状态更新时,组件会重新渲染

还要确保使用 PureComponent,因为它会将重新渲染限制为仅更改的项目

最新更新