Reactjs 如何获取组件列表的累积宽度?

Reactjs 如何获取组件列表的累积宽度?,reactjs,Reactjs,我有一个使用组件显示的“选择”列表。我需要找到所有这些选择的渲染宽度。我的模板如下所示: {props.selections.map((chip: SelectOptionType) => { return ( <Chip text={chip.label} /> ) } {props.selections.map((chip: SelectOptionType, index: number) => { chipsRefs[index] =

我有一个使用组件显示的“选择”列表。我需要找到所有这些选择的渲染宽度。我的模板如下所示:

{props.selections.map((chip: SelectOptionType) => {
   return (
      <Chip text={chip.label} />
   )
}
{props.selections.map((chip: SelectOptionType, index: number) => {
   chipsRefs[index] = React.createRef<HTMLDivElement>();
   return (
      <div ref={chipsRefs[index]}>
         <Chip text={chip.label} />
      </div>
   )
}
我知道做类似事情的建议方法是使用ref,但似乎无法创建ref数组。我试过这样做:

{props.selections.map((chip: SelectOptionType) => {
   return (
      <Chip text={chip.label} />
   )
}
{props.selections.map((chip: SelectOptionType, index: number) => {
   chipsRefs[index] = React.createRef<HTMLDivElement>();
   return (
      <div ref={chipsRefs[index]}>
         <Chip text={chip.label} />
      </div>
   )
}
{props.selections.map((芯片:SelectOptionType,索引:number)=>{
chipsRefs[index]=React.createRef();
返回(
)
}
但我很快就了解到
芯片中的每个Ref都以
null
current
结束

现在我对此有点不知所措,已经尝试过寻找这个用例的示例,但结果是空的。

你能试试这个吗

ref={ref => {
   chipsRefs[index] = ref
}}

尝试这样做:

从“React”导入React;
类选择扩展了React.Component{
建造师(道具){
超级(道具);
这是。_nodes=new Map();
}
componentDidMount(){
这是checkNodes();
}
checkNodes=()=>{
让totalWidth=0;
Array.from(this.\u nodes.values())
.filter(节点=>node!=null)
.forEach(节点=>{
totalWidth=totalWidth+node.offsetWidth;
});
console.log(总宽度);
};
render(){
const{selections}=this.props;
返回(
{selections.map((值,i)=>(
这个。_nodes.set(i,c)}>
{value}
))}
);
}
}
导出默认选择;
  • 我们在
    ref
    prop中定义的函数在
    渲染
  • ref
    回调函数中,
    ref={c=>this.\u nodes.set(i,c)}
    我们传入
    .map()
    提供的索引(i)和html元素 (c) 这是由
    ref
    属性提供的,在本例中是
    div
    本身
  • this.\u nodes.set(i,c)
    将在我们的 这个.u节点是可编辑的,我们创建的每个div对应一对。现在我们已经记录了要使用的HTML元素(节点),这些元素包含了计算渲染列表的
    totalWidth
    所需的所有方法

最后,在
checkNodes()
中,我们得到每个节点的
.offsetWidth
,以获得我们的总宽度。

嘿@Danny实现这一点是否顺利?感谢这些建议。看起来@bkm412为我解决了这个问题。我不确定其他建议是否有效,因为我先使用了两个建议中较短的一个,它似乎完全符合我的要求。