最近做一个操作,点击新建公司,增加公司名称(可取消,保存),通过原生JS去增加节点,此时取消/保存按钮的this指向自身,不能去调用react方法,可以采用挂在在window上
import ReactDOM from 'react-dom';
import React, { Component } from 'react';
import { Button} from 'zent';
export default class station extends React.Component{
constructor(props){
super(props)
<font color='red'>**window["mystation"] = this;**</font> 挂载到window上
this.state={
disbtn:true,
}
<font color='red'> this.addItem=this.addItem.bind(this); 解决this指向</font>
}
<font color='blue'>input输入后需要点击的保存按钮:</font>
saveFn(){
console.log('保存成功');
}
<font color='blue'>点击新建按钮:</font>
addItem(e){
//获取节点,追加填入的input
if(this.state.disbtn){
let btnName=1;
let nextDom=e.target.nextSibling;
let addipt=document.createElement('div');
addipt.className="newitem";
addipt.innerHTML=`
<input placeholder="请输入新增公司名" />
<p><span class="del" onClick={ window["mystation"].saveFn}>取消</span><span class="operation" onClick={this.saveFn}>编辑</span></p>
`;
nextDom.appendChild(addipt);
this.setState({'disbtn':false});
if(btnName==0){
this.setState({'disbtn':true});
}
let netList=document.querySelectorAll('.newitem');
netList.forEach((item,i)=>{
item.className="newitem";
netList.forEach((item2,i2)=>{
netList[netList.length-1].className="newitem focusactive";
netList[netList.length-1].children[0].focus();
});
});
}else{
Notify.clear()
Notify.warn('请先输入新增的公司名');
}
}
render(){
return(
<div id="station" className="maincenter">
<Card style={{ width:'100%' }} title="岗位列表">
<p className="cardtable">
<Card type="nested" title="公司" className="carditem">
<div>
<p className="newadd" onClick={this.addItem}>+新建公司</p>
<div className="addList">
<div className="newitem"><span>这是新增的公司</span>
<p><span className="del">删除</span><span className="operation
">保存</span></p>
</div>
</div>
</div>
</Card>
</p>
</Card>
</div>
)
}
}