答案 0 :(得分:0)
一种方法是在selected
上使用<option>
道具:
export class DataSource extends React.Component<IDataSource, IDataSourceState> {
// ...
private option(item): JSX.Element {
const {idField, captionField} = this.props;
const {[idField]: id, [captionField]: caption} = item;
return
<option
value={id}
key={id}
selected={id===this.props.value}
>
{caption}
</option>
}
这样,我们需要将实际的value
传递到DataSource
中,否则我们的默认值将永远不会更改:
<ComboBox id="TestAsync" label="Country List" onChange={this.changeCountryListValue}>
<DataSource source="/api/region/country" idField="id" captionField="name" selected={this.countryListValue || 'DE'} />
</ComboBox>
或者您可以使ComboBox
来修改嵌套的DataSource
,方法是注入onLoad
回调或提供selected
值,就像我上面直接做的那样。 React.children.map
和React.cloneElement
to rescue on that。
最后,您可以将所有加载数据移出ComboBox
到父元素或某个包装器。我宁愿遵循这种方式,因为当前您的通用名称DataSource
既将数据加载又将项目呈现到<option>
中,这打破了单一责任原则。这可能不允许您在不同的上下文中使用它(说您需要加载相同的数据,但显示在不同的组件中,而不是<option>
)