我遇到了在子React元素发生更改之前强制DOM更改子React元素的问题。
情况如下:
我有一个包含列和行的网格表,然后我有一个Filter元素,它是一个下拉菜单,允许用户按照所需的值过滤网格中的行(即,如果用户选择&#39 ;在“过滤器”菜单中“激活”,然后仅显示具有“活动”值的行。
问题在于,当我单击“过滤器菜单”中的输入时,似乎组件在反映DOM更改(过滤器菜单中的背景更改)之前等待过滤在父网格中完成。这意味着,如果我点击过滤选项,那么在我应用于已检查选项的CSS类之前会出现延迟
代码是这样的:
var Grid = React.createClass({
getInitialState: function () {
return {
rows: _.map(_.range(100000), function (i) {
var state = (i % 2 == 0) ? 'active' : 'inactive';
return {column1: state, column2: i};
})
};
},
_renderRows: function (rows) {
return this.state.rows.map(function(row) {
return <tr><td>{row.column1}</td><td>{row.column2}</td></tr>
});
},
// For the sake of simplicity let's just say we can only filter on the
// values for column1
_onFilterChange: function(value) {
this.setState({
rows: this.state.rows.filter(function (row) { return row.column1 === value })
});
},
render: function () {
return (
<div>
<Filter
handleFilterChange={this._onFilterChange}
/>
<table>
<tbody>
{this._renderRows(this.state.rows)}
</tbody>
</table>
</div>
);
}
});
var Filter = React.createClass({
getInitialState: function () {
return {
selected: {
active: false
}
};
},
componentDidUpdate: function (prevProps, prevState) {
if (this.state.selected !== prevState.selected) {
var value = (this.state.selected['active']) ? 'active' : 'inactive';
this.props.handleFilterChange(value);
}
},
_handleFilterChange: function (value, e) {
optionSelected = {}
optionSelected[value] = e.target.checked;
var newSelected = React.addons.update(this.state.selected, {$merge: optionSelected});
// This should cause a re-render of everything
this.setState({
selected: newSelected,
});
},
render: function () {
return (<ul>
<li>
<input
id='active'
type='checkbox'
value='active'
checked={this.state.selected['active']}
onChange={this._handleFilterChange.bind(this, 'active')}
/>
<label htmlFor='active'>Active</label>
</li>
</ul>);
},
});
在过滤功能发生在父网格中之前,有没有办法强制过滤菜单渲染它的DOM /应用CSS类?