【问题标题】:React ref undefined反应参考未定义
【发布时间】:2020-06-03 05:26:48
【问题描述】:

所以我在 React 中使用 ref 时遇到了一点麻烦。

我要做的就是使用这样的 ref 打印元素的文本内容:

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}

但是,这总是打印 null 或 undefined 而不是我想要的“Hi”。

【问题讨论】:

    标签: reactjs ref


    【解决方案1】:

    你应该使用currentref,比如this.ref.current.textContent

    查看 stackblitz 演示 Here

    export default class App extends Component {
      constructor(props) {
        super(props);
        this.intro = React.createRef();
      }
    
     componentDidMount(){
          console.log( this.intro.current.textContent);
        }
    
     render() {
        return (
          <div ref={this.intro}>Hi</div>
        )
      }
    }
    

    【讨论】:

      【解决方案2】:

      这是因为您将其记录在构造函数中。运行componentDidMount生命周期中的代码。

      export default class SomeClass extends Component {
        constructor(props) {
          super(props);
          this.intro = React.createRef();
      
        }
      
      
      componentDidMount(){
            console.log(this.intro.textContent);
          }
      
        render() {
          return (
            <div ref={this.intro}>Hi</div>
          )
        }
      }
      

      【讨论】:

      • 谢谢,但由于某种原因,当我执行“console.log(this.intro.textContent)”时,我仍然得到空值,即使当我执行“console.log(this.intro )" 我得到了正确的元素。
      • 我什么时候做什么?我没找到你
      • 你可以为它创建一个小提琴或者codepen上的链接吗?
      • 试试 this.intro.current.textContent
      【解决方案3】:

      在实际渲染 Dom 之前,您正在控制台中登录构造函数。 尝试在 onClick 处理程序中登录控制台。

      export default class SomeClass extends Component {
       constructor(props) {
        super(props);
        this.intro = React.createRef();
       }
       print = () => {
         console.log(this.intro.textContent);
       }
       render() {
         return (
           <div>
             <div ref={this.intro}>Hi</div>
             <button onClick={this.print}>Print</div>
           </div>
         )
       }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        • 1970-01-01
        • 2014-12-16
        • 2015-01-14
        • 2023-03-08
        • 1970-01-01
        相关资源
        最近更新 更多