![](/img/trans.png)
[英]React - Draggable components with inputs lose the ability to focus when clicking that input
[英]How to make the input not to lose focus when using state and Function components in ReactJS?
我使用功能組件來渲染組件。 但是無論何時設置狀態,輸入控件都會失去焦點。
如何更改下面的代碼,以使輸入不會失去焦點? 我需要該組件是功能組件。
我的表單上有10個輸入,因此,取決於已更改的文本框,在呈現后應將焦點放在已更改的文本框上。
在changeHandler(event)中,我知道包含目標屬性的事件,該屬性引用更改后的文本框,因此我需要在呈現狀態后將焦點設置為目標輸入元素。
也許我應該定義一個類級變量並將目標設置為該變量。
import React, {Component} from 'react';
export default class PlaybackPassword extends Component{
constructor(props) {
super(props);
this.state = {
setting: {}
}
this.focusElement = null;
this.changeHandler= this.changeHandler.bind(this);
}
componentDidUpdate()
{
if (this.focusElement != null)
this.focusElement.focus();
}
changeHandler(event)
{
this.focusElement = event.target;
var setting = this.state.setting;
setting.SelectedValue = event.target.value;
this.setState({setting : setting});
}
render() {
var parent = this;
function Password(props)
{
return (<div className="password">
<input type="password"
value={props.selectedValue} onChange={parent.changeHandler} />
</div>);
}
return (
<div className="playbackPassword">
<Password selectedValue={this.state.setting.SelectedValue} />
</div>
);
}
}
在示例代碼中,您正在每個渲染上定義(即創建)一個新function Password
。 這意味着您的<Password>
組件每次都是全新的組件。
關鍵是在render
函數之外定義一次函數,以便React可以跟蹤<Password>
組件實際上是兩次render
之間的同一組件。
示例: https : //codesandbox.io/s/nn2nwq2lzp
注意:您將無法使用parent
但需要通過一個道具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.