输入字段的外部点击不起作用

时间:2020-05-10 12:31:12

标签: javascript html reactjs events

我试图在用户单击输入字段之外时隐藏该字段,并在用户单击输入字段时显示该字段。我看到了一些关于stackoverflow的示例,他们说我使用了select d.`name` Department_Name, d.Location, count(*) NumberOfEmployees, sum( coalesce( e.salary, 0 )) as DeptTotalSalary from Department d left join employee e on d.dept_id = e.id group by d.`name` order by count(*) desc, d.`name` ,但在我看来,它仍然无法正常工作。我不知道我在做什么错。

这是我的代码。

e.stopPropagation()

如果我在 class TodoApp extends React.Component { constructor(props) { super(props) this.pasteRef = React.createRef(); this.state = { showPastePopup: false, fname: '' } } onPasteClick = () =>{ this.setState({ showPastePopup: false }) } closePastePopup = e => { console.log("called") this.setState({ showPastePopup:false }) } showPastePopup = e => { e.stopPropagation(); let posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; let posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; this.pasteRef.current.style.left = posx + "px"; this.pasteRef.current.style.top = posy + "px"; this.setState({ showPastePopup: true, }) } render() { return ( <div> <h2>Todos: Some text will be here.........</h2> <span id="pasteBox" ref={this.pasteRef} onClick={this.onPasteClick} className={this.state.showPastePopup ? "showCopyBox control" : "hideCopyBox control"}> paste </span> <div id="pasteArea" className="col w-50 border border-success " onClick={this.closePastePopup}> <div className="mt-1"> First Name: <input onMouseUp={this.showPastePopup} value={this.state.fname || ''} type="text" id="fname" name="fname" /> {this.state.fname} </div> <br/> <div className="mt-1"> Last Name: <input onMouseUp={this.showPastePopup} value='' type="text" id="lname" name="lname" /> </div> <br/> <div className="mt-1"> Address: <input onMouseUp={this.showPastePopup} value='' type="text" id="add" name="add" /> </div> </div> </div> ) } } ReactDOM.render(<TodoApp />, document.querySelector("#app")) 上发表评论,那么它会显示弹出窗口,但是如果用户在输入标签之外单击,如何关闭弹出窗口?

任何帮助将不胜感激。

这是我的jsfiddke

2 个答案:

答案 0 :(得分:0)

问题在于您正在使用不同类型的事件,如果您为两个元素都编写onClick或onMouseUp,则它可以工作。 stopPropagation方法仅停止当前事件。

答案 1 :(得分:-1)

您没有将e传递给方法,也没有将它们绑定到构造函数中。

构造函数应如下所示:

    constructor(props) {
    super(props)
    this.pasteRef = React.createRef();
    this.state = {
      showPastePopup: false,
      fname: ''
    }
    this.onPasteClick = this.onPasteClick.bind(this);
    this.closePastePopup = this.closePastePopup.bind(this);
    this.showPastePopup = this.showPastePopup.bind(this);
  }

当您调用方法时:

<input onMouseUp={e => this.showPastePopup(e)} value='' type="text" id="add" name="add" />