基本上我想从外部脚本向反应组件添加静态HTML。将外部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
“窗口”的行为在不同的做出反应,您可以通过“componentDidMo访问unt()“方法,但不在构造函数中。你必须渲染它,然后一旦组件已被渲染,使用窗口对象 – ayxos
同样的错误它甚至在移动到componentDidMount()后仍然无法工作() –
其中formTarget是ref? –