【发布时间】:2020-03-27 20:03:17
【问题描述】:
我有一个 React 组件,它接收一个具有属性的对象,用于动态生成一些子组件。在生成这些新组件时,我需要为每个组件创建一个引用,但 React.createRef() 将 current 返回为 null。
这是我所做的:
const source = {
component1: {
name: 'Component 1',
active: true
},
component2: {
name: 'Component 2',
active: true
},
component3: {
name: 'Component 3',
active: false
}
}
那么这是主要的组件:
function MyComp(props) {
const {source} = props;
const refs = {};
function makeComps() {
const newComps = [];
Object.keys(source).forEach(x => {
const myRef = React.createRef();
refs[x] = myRef;
newComps.push(
<div ref={myRef}>
<div>Name</div>
<div>{source[x].name}</div>
<div>Active</div>
<div>{source[x].active ? 'Yes' : 'No'}</div>
</div>);
});
return newComps;
}
return (
<>
<strong>{'Brand new components'}</strong>
{source && makeComps()}
{!source && <div>Nothing new</div>}
</>
);
}
然后,当我尝试访问 refs 时,它会返回:
{
component1: {current: null},
component2: {current: null},
component3: {current: null}
}
在某些情况下,我需要这些引用来创建window.scrollTo。根据 React 官方文档,我并没有做任何奇怪的事情。我也尝试使用React.useRef(),但没有。
这是我到达此参考的方式:
const myRef = refs.component3;
window.scrollTo({ behavior: 'smooth', top: myRef.current.offsetTop });
我该如何解决这个问题?我在这里错过了什么?
【问题讨论】:
-
您尝试通过哪种方式访问
refs? 编辑:您的代码对我有用,所有refs都包含它们当前的元素。我无法重现您的问题 -
它不适合我。它让我失去理智。
-
您需要确保在第一次渲染后访问
refs。这很简单,因为 React 在第一次渲染期间不会解析 refs。