我使用 react-bootstrap 库 ( https://react-bootstrap.github.io/components.html#tooltips ),我想连续显示多个 div,每个 div 都有一个工具提示。
{ _.map(blueprint.components, (component, i) => {
const tooltipId = 'tooltip-' + _.replace(blueprint.name, ' ', '-') + '-' + _.replace(component.name, ' ', '-');
const tooltip = (
<Tooltip id={ tooltipId }>
test
</Tooltip>
);
return (
<div>
<OverlayTrigger key={ i } placement='top' overlay={ tooltip }>
<div>
<ImageIcon name={ component.name } size='small'/>
</div>
</OverlayTrigger>
</div>
);
}) }
这是我为实现该目的而编写的一段代码。示例蓝图对象如下所示:
[
{
"id": "123442b4d432d10008c650f7",
"name": "Example Blueprint",
"components": [
{
"name": "Apache",
"module": "apache",
"version": "9000"
}
]
}
]
由于不明原因,我收到“OverlayTrigger”抛出的错误“React.Children.only expected to receive a single React element child.”。
我稍微调试了一下,发现在 OverlayTrigger 内部,this.props.children 是一个数组,我假设它应该是一个对象,但我不知道哪里出了问题. OverlayTrigger 的子项是单个 div。知道错误的原因是什么吗?
编辑: 错误由此抛出:
https://github.com/react-bootstrap/react-bootstrap/blob/master/src/OverlayTrigger.js#L263
children 变量是一个数组而不是一个对象。我不知道为什么。
最佳答案
好的,我发现了问题所在。这是非常具体的案例。
简而言之是这样的:
<SomeOtherComponent>
{ _.map(blueprint.components, (component, i) => {
const tooltipId = 'tooltip-' + _.replace(blueprint.name, ' ', '-') + '-' + _.replace(component.name, ' ', '-');
const tooltip = (
<Tooltip id={ tooltipId }>
test
</Tooltip>
);
return (
<div>
<OverlayTrigger key={ i } placement='top' overlay={ tooltip }>
<div>
<ImageIcon name={ component.name } size='small'/>
</div>
</OverlayTrigger>
</div>
);
}) }
</SomeOtherComponent>
SomeOtherComponent 正在递归地修改它的所有子组件。 简化 SomeOtherComponent 看起来像这样:
const SomeOtherComponent = createClass({
cloneChildrenWithProps(children) {
return React.Children.map(children, child => {
return child;
});
},
render() {
const { children } = this.props;
return (
<div>
{ this.cloneChildrenWithProps(children) }
</div>
);
}
});
这将子项从对象更改为单项数组。
我刚刚将 { this.cloneChildrenWithProps(children) }
替换为 { children }
并解决了问题。
关于javascript - React Bootstrap 工具提示抛出错误 'React.Children.only expected to receive a single React element child.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43527045/