【发布时间】:2023-03-11 07:09:01
【问题描述】:
基本上我想从外部脚本向反应组件添加静态 HTML。
所以我将this 的引用保存到窗口变量如下:
let { PropTypes } = React;
export default class Body extends React.Component {
constructor(){
super();
let frmTrgt={};
frmTrgt.refff=this;
console.log("tthis: ",this);
window.bdyRefrence=frmTrgt;
}
static defaultProps = {
items: []
};
static propTypes = {
items: PropTypes.array.isRequired
};
render() {
return (
<div className={styles.body}>
<h1 className={styles.header}>React Seed</h1>
<p>This is an example seed app, powered by React, ES6 & webpack.</p>
<p>Here is some example data:</p>
<Menu items={this.props.items} />
<div>
<h1>Dynamic Content</h1>
<div id="myDynamicContent"></div>
</div>
</div>
);
}
}
在 INDEX.html(外部脚本)中的脚本标记中,我正在执行以下操作:
function addPHtml() {
try {
window.bdyRefrence.refff.refs.formTarget.insertAdjacentHTML("<p id='mhere'>paragraph 2</p>");
}catch (err){
console.log("err: ",err);
}
}
但是当我调用 addPHtml 时出现以下错误:
err: TypeError: Cannot read property 'insertAdjacentHTML' of undefined
at addPHtml ((index):19)
at <anonymous>:1:1
【问题讨论】:
-
'Window' 在 React 中的行为不同,您可以通过“componentDidMount()”方法访问,但不能在构造函数中访问。您必须渲染它,然后在渲染组件后,使用 window 对象
-
同样的错误 移动到 componentDidMount() 后还是不行
-
你的 formTarget 参考在哪里??
标签: javascript reactjs components