今天工作中使用了这个,感觉很好用啊!
首先: 这个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>
}任何地方都可以用哦。方便吧!开心脸
总结:
1:学习了 unmountComponentAtNode(container), 下载容器中的react组件,返回true或者false
2:学习了 render(element, container), 将react element 渲染在container中。
3:学习了 React.createElement(type, props), 这里使用这个,就只是为了传props。也可以使用React.cloneElement(), type可以是string:'div' 'span' 或者一个react组件(class 或者function)
 
		
 随时随地看视频
随时随地看视频 
				 
				 
				 
				