仔细、细心!!!

输入造成的死循环错误

当想把return 的 GuestGreeting 和 UserGreeting 互换的时候,手动输入两个函数而不是复制粘贴。手动输入把Guest改为User,User改为Guest,当第一个改完,第二个没改完的时候,第二个函数是 xxGreeting,工具会认为是Greeting,因为 Function函数定义的是 Greeting,自己嵌套调用自己会造成死循环。

  1. function Greeting(props) {
  2. const isLoggedIn = props.isLoggedIn;
  3. if (isLoggedIn) {return <GuestGreeting />;}
  4. return <UserGreeting />;}

=> 方法的优点和小细节

优点是可以减少绑定。

  1. constructor(props) {super(props);
  2. this.state= {showModal: false };
  3. this.handleShow = this.handleShow.bind(this);
  4. this.handleHide = this.handleHide.bind(this);}
  5. handleShow () {this.setState({showModal: true});}
  6. handleHide() {this.setState({showModal: false});}

两个方法是等价的。

  1. constructor(props) {super(props);
  2. this.state= {showModal: false };
  3. this.handleShow = this.handleShow.bind(this);
  4. this.handleHide = this.handleHide.bind(this);}
  5. handleShow =()=> {//函数的紫色
  6. this.setState({showModal: true});}
  7. handleHide =()=> {//平常色
  8. this.setState({showModal: false});}

小细节:当多个绑定的时候,从第二个开始,绑定的颜色不会变化,会误以为错误。不必担心

  • 输入造成的错误。在 handleShow的时候,多输入了一个等号,导致一种误解:=>方法只能适用一个和 this等价的方法,不能适用多个,后来发现了这个等号,再次尝试的时候,发现 =>方法适用于多个和this等价的方法。只是从第二个开始方法的颜色不改变
    1. constructor(props) {
    2. super(props);
    3. this.state= {showModal: false };
    4. }
    5. handleShow =()=> {this.setState=({showModal: true});//多输了一个不必要的等号}
    6. handleHide =()=> {this.setState({showModal: false});}

具体实现

  1. class App extends React.Component{
  2. constructor(props) {super(props);
  3. this.state= {showModal: false };}
  4. handleShow =()=> {this.setState({showModal: true});}
  5. handleHide =()=> {this.setState({showModal: false});}
  6. render(){
  7. const modal=this.state.showModal ? (<Modal><div className="modal"><div>
  8. 193909010330</div><br/>194106220345<button onClick={this.handleHide}>Hide Modal
  9. </button></div></Modal>):null;
  10. return(<div className="app">1933<br/><button onClick={this.handleShow}>Show Modal
  11. </button>{modal}</div>);}}
  12. ReactDOM.render(<App />,appRoot);

执行结果
image.pngimage.png

构造函数

class 和function中都有构造函数,function中是默认的,class中是设置默认的初始状态,使用它的原因是render 渲染的方法有生命周期,如果没有生命周期,不需要使用构造函数

render和渲染中的return

class是原生对象,class本身不做 render 渲染,是class中 new 的方法做 render。
render中需要返回值的,即在页面中需要展现的就加return 方法,不需要的就不加return 方法。有些方法需要render,但不需要在页面展现,就不需要return。

class

class不是对象,是原生对象(抽象但,不是对象)。JS可以用 class 把一切不是对象的变成函数对象,所以一切皆对象。和数学可以形成很大的类似。数学可以把一切数据变成对象。