Javascript 对没有挂钩的功能组件作出反应?

Javascript 对没有挂钩的功能组件作出反应?,javascript,reactjs,Javascript,Reactjs,我试图找出元素当前是否可见。问题是我需要一个组件的ref,但它是一个功能组件,因此我得到了错误无法为功能组件提供refs class ShowPosts extends Component { constructor(props) { super(props); this.state = { posts: [], sorting:'desc', lastPostDate:'none', hasMore:false,

我试图找出元素当前是否可见。问题是我需要一个组件的ref,但它是一个功能组件,因此我得到了错误
无法为功能组件提供refs

class ShowPosts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      sorting:'desc',
      lastPostDate:'none',
      hasMore:false,
      pageNumber:0
    };
    this.lastPostRef = React.createRef();
  }
 render(){
  //Irelevant code above
       postList = posts.map((post, k) =>
      {
        if(k===posts.length-1)
          return <PostCard ref={this.lastPostRef} post={post} key={k} />
        return <PostCard post={post} key={k} />
      }
}
...
类ShowPosts扩展组件{
建造师(道具){
超级(道具);
此.state={
员额:[],
排序:'desc',
lastPostDate:“无”,
哈斯莫尔:错,
页码:0
};
this.lastPostRef=React.createRef();
}
render(){
//上面的i相关代码
postList=posts.map((post,k)=>
{
if(k==posts.length-1)
返回
返回
}
}
...
编辑: 我试图找出我是否通过滚动(尝试实现分页)到达该元素,因此我将在我的滚动侦听器中使用它

  onScroll()
  {
    console.log(`Last post is ${this.lastPost}`);
    if(this.lastPostRef)
    {
      var rect = this.lastPostRef.getBoundingClientRect();
      var elemTop = rect.top;
      var elemBottom = rect.bottom;
      console.log(elemTop < window.innerHeight && elemBottom >= 0);//Check if element is visible
    }
  }
onScroll()
{
log(`lastPost是${this.lastPost}`);
if(this.lastPostRef)
{
var rect=this.lastPostRef.getBoundingClientRect();
var elemTop=rect.top;
var elemBottom=矩形底部;
console.log(elemTop=0);//检查元素是否可见
}
}

您可以使用forwardRef在功能组件内传递ref。请检查文档


如果您只是将ref附加到在
明信片
中呈现的DOM元素上,它看起来应该能满足您的期望

return <PostCard ref={this.lastPostRef} post={post} key={k} />
因此,明信片将ref作为道具,并将其作为道具传递给渲染的元素

如果需要,还可以使用条件运算符而不是
If
来减少重复性。在
showPosts
中:

{
  <PostCard
    ref={k === posts.length - 1 ? this.lastPostRef : null}
    post={post}
    key={k}
  />
}
{
}

你想使用ref做什么?你能告诉我还有什么地方使用了
lastPostRef
。@CertainPerformance是的,我会编辑这个问题
return <PostCard theRef={this.lastPostRef} post={post} key={k} />
const PostCard = ({ theRef, post }) => {
  // ...
  return (
    <div ref={theRef}>
{
  <PostCard
    ref={k === posts.length - 1 ? this.lastPostRef : null}
    post={post}
    key={k}
  />
}