这是场景。我已经使用 jQuery Datable插件创建了表格。在最后一列中,所有行都有一个按钮(一个 non react HTML元素)。由于表格的所有HTML都是由插件自动创建的,因此我们不能将JSX组件用作按钮,因此不能使用 onClick 反应监听器。
这是我目前正在做的事情:
在我的常规脚本文件中(无反应):
$(document).on("click", ".my-button", function(){
//show a popup and add content in it using ajax
});
这就是我想在React代码中做的相同的事情(即在主要组件类中)
class LoginForm extends React.Component {
constructor(props) {
super(props);
}
//following method is to be called on onClick
showAPopupAndAddContentAjax() {
//code
}
//other stuff
}
那么有什么方法可以调用任何React监听器方法吗?还是有其他方法可以实现这一目标?
PS:我现在暂时无法删除数据表代码,因为它已经被编写并且现在不能被替换。只需要 onClick
这样的听众答案 0 :(得分:1)
通常,您不能这样做。因为React在虚拟dom概念上工作,所以您想与核心dom进行交互。
一种棘手的方法是添加类并触发弹出窗口打开:
$(document).on("click", ".my-button", function(){
$('#your_instance_of_component').addClass('open-popup');
});
// in your react app
const openPopup = ReactDOM.findDOMNode(LoginForm)
.getElementsByClassName('open-popup')//[0]
// implement the logic
if(openPopup.length) {
// do the stuff
}
希望,这会有所帮助!
更新
我刚刚有了另一个可以正常工作的想法:
在jQuery侦听器中,添加查询参数。并且在react应用中,您可以在路由更改时调用dom侦听器。您必须通过一些研究为此付出努力。希望这对您有帮助!
答案 1 :(得分:0)
onmousedown onmouseup
如果使用jQuery,还有其他方法:
$('#SomeButton').click(function() {
functionTOevent();
});
*使用与此相同的想法,使事情有所反应。
答案 2 :(得分:0)
设置一个事件侦听器,React侦听并基于此事件更新状态。 该代码段应为您提供大致的思路。
$(document).on("click", ".my-button", function() {
//show a popup and add content in it using ajax
$(document).trigger( "show-my-react-popup" );
});
class Popup extends React.Component {
state = { open: false };
showAPopupAndAddContentAjax = () => {
this.setState({ open: true });
};
closePopup = () => {
this.setState({ open: false });
};
componentDidMount() {
// jQuery code, should be refactored and removed in the future
$(document).on("show-my-react-popup", () => {
this.showAPopupAndAddContentAjax();
});
}
componentWillUnmount() {
// jQuery code, should be refactored and removed in the future
$(document).off("show-my-react-popup");
}
render() {
if (!this.state.open) return null;
return (
<div className="popup">
<p>popup</p>
<button onClick={this.closePopup}>close</button>
</div>
);
}
}
答案 3 :(得分:0)
不建议将使用虚拟DOM(React)的框架与使用物理DOM(jQuery)的框架一起使用。
但是,我们只能在应用程序的一部分中呈现React,这避免了同时使用物理/虚拟DOM的大量风险。
我认为类似这样的方法可能适用于您的用例。
HTML
<button class="my-button">Render Component</button>
<div id="root"></div>
Javascript:
class App extends React.Component {
static getDerivedStateFromProps(props, state) {
// load data with ajax
}
render() {
return (
<div>
<h1>Hello World</h1>
<p>This is a react component</p>
</div>
);
}
}
function renderReact() {
ReactDOM.render(
<App />,
document.getElementById('root')
);
}
$(document).on('click', '.my-button', function() {
renderReact();
});