react -- Dom 与 事件

Dom节点用的比较少。但是先研究下还是有用处的,万一哪个功能react不好实现,我们还能用自己强大的原生编程完成。

先说下 添加HTML

。哦。对这个也是比较偏门的

Code

// 插入
dangerouslySetInnerHTML={createMarkup()}
// 声明
function createMarkup() {
  return {__html: '<h2 style="color: #ddd">HTML</h2>'};
}

事件绑定Call

一般是这样的

  constructor(props) {
    super(props)
    this.state = {msg: 'Home Page', index: true}
        
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(e) {
    this.setState(prevState => ({
      msg: prevState.index ? 'Home Page' : 'Updata Home done',
      index: !prevState.index
    }));
  }

返回bind。。这个写法好恶心啊!
写一个还记得,两个,三个,每个都要复制粘贴,不专业的人看出来这是傻逼操作。

这样改下声明的函数:

handleClick = (e) => {
    this.setState(prevState => ({
      msg: prevState.index ? 'Home Page' : 'Updata Home done',
      index: !prevState.index
    }));
  }

不过,这样会生成回调,每次都会重新渲染,大多数情况下是可以这样用的,但是传给子组件以及更下级组件的时候,就会浪费性能。

我不知道这样翻译对不对,官方的说法:
The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the property initializer syntax, to avoid this sort of performance problem.

<br />


参考链接: https://facebook.github.io/react/docs/refs-and-the-dom.html

--END--
<br />

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 自己最近的项目是基于react的,于是读了一遍react的文档,做了一些记录(除了REFERENCE部分还没开始读...
    潘逸飞阅读 9,012评论 1 10
  • It's a common pattern in React to wrap a component in an ...
    jplyue阅读 8,549评论 0 2
  • “这样下去有意思吗?”小颖对阿浩说。 阿浩答不上来这样到底有没有意思,他听到小颖的一声“再见”和随之而来的忙音。 ...
    讲个故事给你听吧阅读 4,453评论 0 50
  • 1.从官网下载安装包 https://nodejs.org/zh-cn/download 2.下载包 当前版本 n...
    火星人想回火星阅读 1,616评论 0 0

友情链接更多精彩内容