reactjs - 在创建动态生成的组件时反应 createRef 返回 current = null
问题描述
我有一个 React 组件,它接收一个具有动态生成一些子组件的属性的对象。在生成这些新组件时,我需要为每个组件创建一个 ref,但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 });
我该如何解决这个问题?我在这里想念什么?
解决方案
我假设您在第一次渲染完成之前尝试访问它们。在这种情况下,您的组件没有安装。确保它是,使用useEffect
钩子。在这里了解更多。
function MyComp({ source, ...props }) {
const refs = {};
function makeComps() {
const newComps = [];
Object.keys(source).forEach((x, idx) => {
const myRef = React.createRef();
refs[x] = myRef;
newComps.push(
<div key={idx} ref={myRef}>
<div>Name</div>
<div>{source[x].name}</div>
<div>Active</div>
<div>{source[x].active ? 'Yes' : 'No'}</div>
</div>
);
});
return newComps;
}
useEffect(() => {
// here, your component did mount
// try to access component1 using the optional
// chaining feature of JavaScript
console.log(refs.component1?.current);
}, [refs]);
return (
<>
<strong>{'Brand new components'}</strong>
{source && makeComps()}
{!source && <div>Nothing new</div>}
</>
);
}
推荐阅读
- android - 无法使用改造默认回调显示来自 API 的图像和文本
- google-cloud-functions - 启动数据流作业的云功能的动态输入
- docker - 错误:找不到本地工作区文件('angular.json')。使用 docker-compose up 命令时
- python - 自定义颜色图
- java - Retrieve multiple data from Firebase to my Android applciation
- numpy - 如何使用 numpy + gfortran 链接静态库
- php - 即使从数据库中删除条目后,Laravel 护照刷新令牌仍然有效
- console - 我在哪里可以找到 lite-server 的控制台日志?
- sql-server - 如何使用 SQL Server Soundex
- angularjs - 如何允许 angularJS 自定义过滤器单次操作数据