html从外部引入react组件不生效,从React组件中的外部加载的HTML访问内部函数

小编典典

使用“ 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值