class F1 extends React.Component{
hot(){
alert("Hot function running");
}
lot(){
let t = this;
ReactDOM.render(<F2 yF={() => {
t.hot();
}} />,document.getElementById("b"));
}
render(){
return (
<button onClick={this.lot}>F1 click</button>
);
}
}
class F2 extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<button onClick={this.props.yF}>F2 click</button>
);
}
}
ReactDOM.render(<F1 />,document.getElementById("a"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="a"></div>
<div id="b"></div>
</body>
</html>
You can see a nice illustration here
当我点击 class F1
时,我想调用Button F2
内的函数来执行F1中的函数。
目前我试图将功能从F1传递到F2,但它无法正常工作
简化......
点击hot
F1
内拨打F2
个功能
答案 0 :(得分:0)
您需要在constructor
方法中将lot方法绑定到此方法。然后只有它才能得到上下文
class F1 extends React.Component{
constructor() {
super();
this.lot = this.lot.bind(this);
}
hot(){
alert("Hot function running");
}
lot(){
ReactDOM.render(<F2 yF={() => {
this.hot();
}} />,document.getElementById("b"));
}
render(){
return (
<button onClick={this.lot}>F1 click</button>
);
}
}
class F2 extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<button onClick={this.props.yF}>F2 click</button>
);
}
}
ReactDOM.render(<F1 />,document.getElementById("a"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="a"></div>
<div id="b"></div>
</body>
</html>