【发布时间】:2017-12-07 06:31:41
【问题描述】:
我正在尝试构建一个反应网格组件,其设计类似于图中所示。
(1) 有人将原始数据作为道具传递给网格,(2) 将其转换为多个 GridData 对象并存储在 GRID 中。 (3) 这些对象在render 函数中迭代以呈现网格项。 (4) 现在,有人在网格之外执行了一个动作(可能在工具栏或其他地方),触发存储在 Grid 中的一些/所有 GridData 对象的属性更改(在本例中为select all)。 (5) 这会导致所有网格项目都获得更新的属性(在这种情况下,所有项目都将被选中)。
但是,当我在 Grid 中更新对象的属性时,子 (GridItem) 不会选中复选框。我该如何解决?
设计代码如下所示:
Grid.js
class Grid extends Component {
constructor(props) {
super(props);
this.state = {
gridData: props.data,
};
}
componentWillReceiveProps(nextProps) {
this.setState({
gridData:
typeof nextProps.gridData !== 'undefined' && nextProps.gridData
? nextProps.gridData
: this.state.gridData,
});
}
// PubSub System to receive notification
subscriber(msg, data) {
if(msg === 'SELECT_ALL_ITEMS'){
this.state.gridData.forEach(gridItem => {
gridItem.setChecked(true);
}
}
renderGridItem(gridItem) {
return (
<GridItem
key={gridItem.getItemId()}
title={gridItem.getTitle()}
isChecked={gridItem.isChecked()}
/>
);
}
render() {
return (
<div>
{this.state.gridData !== 'undefined' && this.state.gridData ? (
this.state.gridData.map(gridItem => this.renderGridItem(gridItem))
) : (
<div />
)}
</div>
);
}
}
GridItem.js
class GridItem extends Component {
constructor(props) {
super(props);
this.state = {
isChecked: typeof props.isChecked !== 'undefined' && props.isChecked ? props.isChecked : false,
title: typeof props.title !== 'undefined' && props.title ? props.title : '',
},
};
}
render() {
const { classes } = this.props;
return (
<div>
<Checkbox
checked={this.state.isChecked}
/>
{this.state.properties.title}
</div>
);
}
}
GridData.js
export default class GridData {
constructor(item) {
this._title = item.title;
this._itemId = item.itemId;
}
getItemId() {
return this._entryId;
}
isChecked() {
return this._isChecked;
}
setChecked(isChecked) {
this._isChecked = isChecked;
}
getTitle() {
return this._title;
}
}
【问题讨论】:
-
<Checkbox checked={this.state.isChecked}/>改为<Checkbox checked={this.props.isChecked}/> -
@Madhavan.V 这也不起作用。出于某种原因,
subscriber函数中的更改不会被 React 拾取。
标签: javascript reactjs react-redux publish-subscribe