使用 "dangerouslySetInnerHTML" 是......"dangerous" 作为它的名字 ^^,这实际上也不是纯粹的 React 方式。
但是,如果你必须这样做,你可以做这样的事情(利用 React 内置的 jQuery 是默认的)
======
来自此处的编辑版本:(仅使用 1 个组件)
export default class MyComponent extends Component {
componentDidMount() {
// using jQuery to manipulate DOM element form third-party source
// NB. you may think of using setTimeout here, to wait for the external source to be fully loaded here, of course it's not so safe
// but anyway, we are using "dangerouslySetInnerHTML" anyway => quite dangerous, though ^^
// setTimeout(function(){
$(document.findElementsByTagName("span")[0]).click(function(e){
// or perhaps $("#spanID").click if you can, just be careful between DOM element and react component
e.preventDefault();
// DO SOMETHING HERE, just like you do in the window.onload function
// or maybe you also need to get param values by getting $(this).data("...") or $(this).attr("ATTRIBUTE-NAME")
return false;
});
// });
}
render() {
return (
<div
dangerouslySetInnerHTML={{ __html: this.props.externalHTML }}
/>
);
}
}
======
来自这里的旧答案:(使用 2 个组件)
父组件:
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.callbackOnThisComponent = this.callbackOnThisComponent.bind(this);
}
callbackOnThisComponent(param1, param2, param3) {
// do whatever you like with the above params
}
render() {
return (
<ChildComponent triggerCallbackOnParent={this.callbackOnThisComponent} />
);
}
}
子组件:
export default class ChildComponent extends Component {
componentDidMount() {
// using jQuery to manipulate DOM element form third-party source
let that = this;
// NB. you may think of using setTimeout here, to wait for the external source to be fully loaded here, of course it's not so safe
// but anyway, we are using "dangerouslySetInnerHTML" anyway => quite dangerous, though ^^
$(document.findElementsByTagName("span")[0]).click(function(e){
// or perhaps $("#spanID").click if you can, just be careful between DOM element and react component
e.preventDefault();
that.props.triggerCallbackOnParent(param1, param2, param3);
// or maybe you need to get param values by getting $(this).data("...") or $(this).attr("ATTRIBUTE-NAME")
return false;
}, that);
}
render() {
return (
<div
dangerouslySetInnerHTML={{ __html: this.props.externalHTML }}
/>
);
}
}
我只是使用React的主要思路,将props向下传递给子组件,当你想从子组件向上触发一个函数时,在父组件上创建一个回调函数。供您或任何其他人参考,这是我关于如何将回调函数从父组件传递到多级子组件的演示:
强制 React 容器刷新数据
重定向时重新初始化类
如果这还不起作用,请随时向我展示一些错误日志,谢谢