当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ReactDom

ReactDom

2018年12月14日  | 移动技术网IT编程  | 我要评论

今天工作中使用了这个,感觉很好用啊!

首先: 这个reactdom是干嘛用的?

答: 

  react-dom 包提供了 dom 特定的方法,可以在你的应用程序的顶层使用,如果你需要的话,也可以作为 react模型 之外的特殊操作dom的接口。 但大多数组件应该不需要使用这个模块。

 

其次: 如何引用?

答:

  如果你使用 es6 与 npm ,你可以写 import reactdom from 'react-dom', 或者:import { render, unmountcomponentatnode } from 'react-dom'

 

再问: 有哪些接口?可以干嘛?

答:

一共有五个接口,

render()

hydrate()

reactdom.render(element, container[, callback])
// 渲染一个 react 元素到由 container 提供的 dom 中,并且返回组件的一个 引用(reference) (或者对于 无状态组件 返回 null )

unmountcomponentatnode()

reactdom.unmountcomponentatnode(container)
// 从 dom 中移除已装载的 react 组件,并清除其事件处理程序和 state 。 如果在容器中没有挂载组件,调用此函数什么也不做。 如果组件被卸载,则返回 true ,如果没有要卸载的组件,则返回 false 

finddomnode() 不建议使用

reactdom.finddomnode(component)
// 如果组件已经被装载到 dom 中,这将返回相应的原生浏览器 dom 元素。在大多数情况下,你可以绑定一个 ref 到 dom 节点上,从而避免使用finddomnode。

createportal()  这个很有用处,啊啊啊!

reactdom.createportal(child, container)
// 创建一个 插槽(portal) 。 插槽提供了一种方法,可以将子元素渲染到 dom 组件层次结构之外的 dom 节点中

 

实例: 背景,我希望在任意页面 点击一个按钮,都可以打开同一个模态框。那么我希望只写一个方法,其他按钮点击触发这个方法,这个方法会把模态框渲染。

上代码:

export const onpenregistration = (props = {}) => {
  const div = document.createelement('div') // create一个容器
  const obj = { // 这个模态框还需要消失,也就是卸载,因此需要传unmountcomponentatnode()方法
    removecontaindiv: () => {
      unmountcomponentatnode(div)
      document.body.removechild(div)
    }
  }
  const registration = react.createelement(notification, { ...props, ...obj }) // 这个是使用createlement()方法,create一个react element
  render(registration, div) // render第一个参数是reactelement,第二个是容器,这一步实现了在这个div容器中渲染notification元素
  document.body.appendchild(div) // 将divappend到body中
}

notification是一个普通的react元素:

class register extends component {
    constructor (props) {
     super(props)
     this.state = {
      show: true
     }
    }
    render () {
      const { show } = this.state
      const { removecontaindiv } = this.props
      return(
          <div onclick={removecontaindiv}>hshshs</div>
      )
    }
}

现在就可以使用onpenregistration方法了:

import { openindicatorregistration } from './indicatorregistration'

render(){
 <button onclick={openindicatorregistration}>
    打开注册模态框
</button>
}

任何地方都可以用哦。方便吧!开心脸

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网