【发布时间】:2017-03-08 14:18:03
【问题描述】:
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>
https://jsbin.com/poqofohiqa/edit?html,js,console,output
当我单击 Button F2 时,我想调用class F1 中的函数,应该执行F1 中的函数。
目前我正在尝试将函数从 F1 传递到 F2 但它不起作用
更新 1
为了简单...
我试图通过单击F2 上的按钮在F1 中调用hot 函数
【问题讨论】:
-
ReactDOM.render要求什么? -
lot函数不应该做它实际做的事情(调用ReactDOM.render)。您应该在组件之外执行此操作。 -
它似乎有效。单击 F1 按钮会添加 F2 按钮。单击 F2 按钮会触发警报。
-
是的 - 它正在工作。你是什么意思它不起作用?
-
我不清楚所有这段代码应该做什么。
标签: javascript function class reactjs methods