react怎么做到点击页面上的某个按钮,而不是在改变state或props值的情况下,重新获得render之后的元素属性?

react在本身状态改变的前提下,包括state和props改变,都会重新render。

问题:如果需要在页面点击一个按钮,操作dom元素的属性,怎么去获取dom元素的点击之后的最新属性呢?

可以在生命周期函数componentDidUpdate里面去获取更新渲染后的DOM元素,因为componentDidUpdate是组件更新再渲染结束之后执行,不过在初始化render时不执行。

但是操作不当会造成死循环,因为如果在 componentDidMount 里面 setState 导致组件更新,组件更新后会执行 componentDidUpdate,此时如果又在 componentDidUpdate 里面 setState 又会导致组件更新,就会造成死循环了。要避免死循环,需要谨慎的在 componentDidUpdate 里面使用 setState

posted @ 2020-01-06 15:21  半忧夏  阅读(795)  评论(0编辑  收藏  举报