我有一个名为ButtonContainer
的容器组件,它将两位状态传递给按钮显示组件。问题是,容器需要传递使用dispatch
的onclick函数,但我不知道如何访问它。请参阅下面的代码。我怎样才能访问派遣?
import React from 'react'
import { connect } from 'react-redux'
import { fooAction , barAction } from '../foobarActions.js'
import ButtonComponent from './ButtonComponent.jsx'
const mapStateToProps = (state) => {
var buttonText = this.state.foo + this.state.bar
var buttonOnClick = function(e, coord) {
e.preventDefault()
if (e.nativeEvent.which === 1) { // left click
dispatch(fooAction);
} else if (e.nativeEvent.which === 3) {
dispatch(barAction); // right click
} else {
console.log("Unknown click");
}
}
return {
buttonText: buttonText
buttonOnClick: buttonOnClick
}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
const ButtonContainer = connect(
mapStateToProps,
mapDispatchToProps
)(ButtonComponent)
export default ButtonContainer;
答案 0 :(得分:2)
这是在mapDispatchToProps
函数中完成的,但你应该离开"点击"表示组件中的逻辑(ButtonComponent
)。
class ButtonComponent extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault()
if (e.nativeEvent.which === 1) { // left click
this.props.leftClick();
} else if (e.nativeEvent.which === 3) { // right click
this.props.rightClick();
} else {
console.log("Unknown click");
}
}
render() {
return <button onClick={this.handleClick}>{this.props.buttonText}</button>
}
}
const mapStateToProps = (state) => {
return {
buttonText: this.state.foo + this.state.bar
}
}
const mapDispatchToProps = (dispatch) => {
return {
leftClick: () => dispatch(fooAction),
rightClick: () => dispatch(barAction)
}
}
const ButtonContainer = connect(
mapStateToProps,
mapDispatchToProps
)(ButtonComponent)
export default ButtonContainer;