深入React源码揭开渲染更新流程的面纱
    		       		warning:
    		            这篇文章距离上次修改已过448天,其中的内容可能已经有所变动。
    		        
        		                
                
import React from 'react';
import ReactDOM from 'react-dom';
 
class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }
 
  handleClick() {
    this.setState({ liked: !this.state.liked });
  }
 
  render() {
    const text = this.state.liked ? '喜欢' : '点击喜欢';
    return (
      <button onClick={() => this.handleClick()}>{text}</button>
    );
  }
}
 
ReactDOM.render(
  <LikeButton />,
  document.getElementById('like_button_container')
);这段代码定义了一个名为LikeButton的React组件,它有一个状态属性liked,当按钮被点击时,会通过handleClick方法改变这个状态。render方法根据liked的值返回不同的文本,创建一个按钮元素。最后,这个组件被渲染到页面上的一个like_button_container元素中。这个例子展示了React中最基本的状态更新流程。
评论已关闭