小编典典
使用“ 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 (
dangerouslySetInnerHTML={{ __html: this.props.externalHTML }}
/>
);
}
}
=====
此处的旧答案:(使用2个组件)
ParentComponent:
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:
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 (
dangerouslySetInnerHTML={{ __html: this.props.externalHTML }}
/>
);
}
}
我只是使用React的主要思想,即将props向下传递给子组件,并且当您想从子组件向上触发函数时,请在parent上创建一个回调函数。
如果仍然无法解决问题,请随时向我显示一些错误日志,谢谢
2020-07-22