一、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);
}