React 組件內方法

一、React  組件內方法自動執行

組件內寫了隱藏右部的方法,

 hideRight() {
      this.setState({
         record: {},
      });
   }

點擊事件如下

          onClick={this.hideRight()}

如上寫法hideRight每次都會自動執行

 正確寫法

1. onClick={this.hideRight}

2.onClick={this.hideRight.bind(this)}

import React from 'react'
import './index.less'
import {connect} from "react-redux";
import {data} from "./constants";
import {Base, InfoWindow, Label, Map, Marker} from "rc-bmap";
import RightBoard from "./right";
import {Icon} from 'antd';

const {Point, Size, Events} = Base;
const {Content} = Label;


class Dashborad extends React.Component {

   constructor(props) {
      super(props);
      this.state = {
         modalVisible: false,
         style: leftStyle,
         record: {},
      };
   }
   hideRight() {
      this.setState({
         record: {},
      });
   }
   render() {
      const children = this.getMakers();
      return (
         <div className="dashboard">
            {
               this.state.record.msg &&
               <div className="right">
                  <Icon type="close" onClick={this.hideRight}/>
                  <RightBoard data={this.state.record.msg}/>
               </div>
            }
         </div>
      )
   }
}

function mapStateToProps(state) {
   return {
      auth: state.auth,
      dashboard: state.dashboard,
      loading: state.loading,
      error: state.error,
      session: state.session
   }
}

export default connect(mapStateToProps)(Dashborad);

二、組件內方法如何訪問組件state

在constructor裏綁定方法

constructor(props) {
   super(props);
   this.state = {
      modalVisible: false,
      style: leftStyle,
      record: {},
   };
   this.hideRight = this.hideRight.bind(this);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章