React入门0x016: 访问Dom

发布时间:2019-08-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React入门0x016: 访问Dom脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

0x000 概述

不到必要不要在React中访问Dom,尝试使用React的思想去解决问题。当然,必要的时候还是可以的,比如某些依赖Dom的组件

0x001 时机

React中,并不是任何时候都可以访问Dom的,需要讲究时机。因为React中的组件存在生命周期,必须要在Dom 挂载之后的生命周期才能访问到Dom,也就是componetnDidmount之后

  • 栗子:

    class App extends React.Component {
        constructor() {
            super()
            console.log('constructor', document.getElementById('cool'))
        }
    
        componentDidMount() {
            console.log('componentDidMount', document.getElementById('cool'))
        }
    
        render() {
            return <div id='cool'>
                Dom
            </div>
        }
    }
  • 输出:

    React入门0x016: 访问Dom

0x002 访问方式

  • 传统方式
    传统方式就是上面栗子中那般,直接在componentDidMount之后使用传统方式访问
  • refs
    ref有两种方式

    • ref属性绑定变量,这种方式需要先调用React.createRef创建一个ref,然后在componentDidMount之后的生命周期中使用this.myRef.current来访问。

      class App extends React.Component {
          constructor() {
              super()
              this.myRef = React.createRef();
          }
      
          componentDidMount() {
              const node = this.myRef.current;
              console.log('componentDidMount',node)
          }
      
          render() {
              return <div ref= {this.myRef}>
                  Dom
              </div>
          }
      }

      效果

      React入门0x016: 访问Dom

    • 绑定函数,更简约一点,可以直接使用myRef访问

      class App extends React.Component {
          constructor() {
              super()
          }
      
          componentDidMount() {
              console.log('componentDidMount',this.myRef)
          }
      
          render() {
              return <div ref= {(e)=>this.myRef=e}>
                  Dom
              </div>
          }
      }

      效果

      React入门0x016: 访问Dom

0x003 总结

不到必要不要在React中访问Dom,尝试使用React的思想去解决问题。

脚本宝典总结

以上是脚本宝典为你收集整理的React入门0x016: 访问Dom全部内容,希望文章能够帮你解决React入门0x016: 访问Dom所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。