【发布时间】:2019-10-08 17:49:07
【问题描述】:
import React from "react";
import OtherComponent from "./OtherComponent";
class Main extends React.Component {
constructor(props) {
super(props);
this.runMyFunction = this.runMyFunction.bind(this);
this.myFunction = this.myFunction.bind(this);
}
runMyFunction(event) {
event.preventDefault();
this.myFunction();
}
myFunction() {
return console.log("I was executed in Main.js");
}
render() {
return (
<div>
<OtherComponent runMyFunction={this.runMyFunction} />
</div>
);
}
}
export default Main;
import React from "react";
class OtherComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.runMyFunction();
}
render() {
return (
<div>
<button onClick={this.handleClick} />Click me to execute function from Main </button>
</div>
);
}
}
export default OtherComponent;
我是 redux 的新手,不知道如何在其他组件中传递和运行该函数。不使用 redux 很容易,只需像上面的示例一样作为 props 传递。 我有包含操作、组件、容器和减速器的文件夹。
现在我有Main.js 我有的地方
import React from "react";
const Main = ({data, getData}) => {
const myFunction = () => {
return "ok";
};
return (
<div>
<p>This is main component</p>
</div>
);
};
export default Main;
在MainContainer.js 我得到了:
import Main from "../../components/Main/Main";
import { connect } from "react-redux";
import {
getData
} from "../../actions";
function mapStateToProps(state) {
return {
data: state.main.data
};
}
const mapDispatchToProps = (dispatch) => {
return {
getData: () => dispatch(getData())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Main);
那么我如何在 OtherComponent.js 中运行函数 myFunction():
import React from "react";
const OtherComponent = ({executeFunctionInMainComponent}) => {
return (
<div>
<button onClick={executeFunctionInMainComponent}>run action</button>
</div>
);
};
export default OtherComponent;
我只需要运行,而不是传递整个函数,只需在 Main.js 中执行 myFunction,但运行此函数的操作将来自 OtherComponent。
【问题讨论】:
-
感谢您尝试帮助我。这不是我想做的。我刚刚编辑了我的帖子,添加了更多描述。
标签: reactjs react-redux react-hooks