如何使用ref in(条件渲染)

时间:2019-09-25 09:22:05

标签: javascript reactjs conditional-statements render ref

我想使用ref,但是我不能在最初为假的条件渲染中使用它。

constructor(props) {
    super(props);
    this.state = { 
      filterActive: false,
    }
    this.firstRef = React.createRef();

}

如果我在此使用ref:-

{this.state.filterActive ?
    <label ref={this.firstRef}>Time Range</label>
:null}

引用为空。

3 个答案:

答案 0 :(得分:1)

怎么样呢?

// directly assign the element to this.firstRef
// instead of doing it in the constructor
    <label
      ref={(elem) => (this.firstRef = elem)}
      style={{display: this.state.filterActive ? 'inline-block' : 'none'}}
    >
      Time Range
    </label>

,并且在使用this.firstRef时,将您放在一个if这样的内部:

if (this.firstRef) {
// your work
}

答案 1 :(得分:0)

尝试一下

render(){
 return(
{this.state.filterActive ? (<label ref={this.firstRef}>Time Range</label>) : (null)}
)}

答案 2 :(得分:0)

兄弟们! 我面临着同样的问题,但是我正在使用钩子。 我找到了替代解决方案。通过使用Intersection Observer,我们可以解决它。

在挂钩中,使用“ react-intersection-oberserver”中的“ useInView”挂钩,

//使用对象销毁,因此您无需记住确切的顺序

const { ref, inView, entry } = useInView(options);

//或数组销毁,可轻松自定义字段名称

const [ref, inView, entry] = useInView(options);

在您的DOM节点上附加“ ref”,无论您的DOM节点是否在View中,“ inView”都将返回一个布尔值,而“ entry”将提供对DOM节点属性的访问权限。

import React from 'react';
import { useInView } from 'react-intersection-observer';
 
const Component = () => {
  const { ref, inView, entry } = useInView({
    /* Optional options */
    threshold: 0,
  });
 
  return (
    <div ref={ref}>
      <h2>{`Header inside viewport ${inView}.`}</h2>
    </div>
  );
};

希望这会有所帮助,它可以解决我的问题。

对于基于类的组件,请阅读:https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API