gpt4 book ai didi

javascript - 为什么 React 会更新这部分 DOM?

转载 作者:行者123 更新时间:2023-11-28 07:17:27 24 4
gpt4 key购买 nike

假设我有这个组件:

var React= require("react");

var LikeButton= React.createClass({
getInitialState: function(){
return {liked: false};
},

handleClick: function(event){
this.setState({liked: !this.state.liked});
},

render: function(){
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<div>
<h1>{new Date().toTimeString()}</h1>
<p onClick={this.handleClick}>
You {text} this. click to toggle.
</p>
</div>
);
}
});

React.render(<LikeButton/>, document.getElementById('mount'));

当我触发 onClick 事件时,h1 元素会使用当前日期进行更新,为什么?

最佳答案

当组件的状态发生更改时,其 render 方法将触发。

来自React documentation :

setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

关于javascript - 为什么 React 会更新这部分 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30697235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com