Javascript 如何在React中5毫秒后隐藏输入文本?
有人能帮我切换功能吗?我有一个密码输入框 来自API,现在点击输入字段中的眼睛按钮,需要显示secretid 对于5ms和id,应在计时器后自动设置为“******”Javascript 如何在React中5毫秒后隐藏输入文本?,javascript,reactjs,Javascript,Reactjs,有人能帮我切换功能吗?我有一个密码输入框 来自API,现在点击输入字段中的眼睛按钮,需要显示secretid 对于5ms和id,应在计时器后自动设置为“******” const HideID = "****************"; togglePassword = () => { const currentSecretID = this.state.secretID ? this.state.secretID : "********&
const HideID = "****************";
togglePassword = () => {
const currentSecretID = this.state.secretID
? this.state.secretID
: "********";
setTimeout(() => {
this.setState({
secretID: currentSecretID,
showID: !this.state.showID,
});
}, 10);
setTimeout(() => {
this.setState({
secretID: HideID,
});
}, 100);
//clearInterval(50)
})
输入字段看起来像
我在函数中哪里做错了?
…需要显示5毫秒
这里有几个问题:
// Handling the click, we just set the information to display
onEyeClick() {
this.setState({
secretID: currentSecretID,
showID: !this.state.showID,
});
}
// Watch for component updates
componentDidUpdate() {
if (this.state.showID && !this.waitingToHideID) {
// The component updated to start showing the ID; wait to hide it and remember we're doing that
this.waitingToHideID = true;
requestAnimationFrame(() => {
// The browser is *about* to update the display; wait 100ms after this
// so the human can see it
setTimeout(() => {
// It's been 100ms, hide it again
this.setState({
secretID: HideID, // *** Why? What makes state less secure thatn `currentSecretID`?
showID: false,
});
this.waitingToHideID = false;
}, 100);
});
}
}
实例:
让currentSecretID=“秘密”;
const HideID=“*************”;
类示例扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
秘密的:希德,
showID:错,
};
this.onEyeClick=this.onEyeClick.bind(this);
}
//在处理点击时,我们只需设置要显示的信息
onEyeClick(){
这是我的国家({
秘密的,秘密的,
showID:!this.state.showID,
});
}
//注意组件更新
componentDidUpdate(){
if(this.state.showID&!this.waitingtohide){
//组件已更新,开始显示ID;请等待将其隐藏,并记住我们正在这样做
this.waitingtohide=true;
requestAnimationFrame(()=>{
//浏览器*即将*更新显示;请在此之后等待100毫秒
//这样人类才能看到它
设置超时(()=>{
//已经100毫秒了,再把它藏起来
这是我的国家({
秘密的:隐藏的,//***为什么?是什么使得国家不那么安全?
showID:错,
});
this.waitingtohide=false;
}, 100);
});
}
}
render(){
const{secretID,showID}=this.state;
返回(
ID:{secretID}
);
}
}
render(,document.getElementById(“根”))代码>
正如其他答案所建议的,React DOM通常需要一些时间来重新呈现和更新DOM中的数据。我建议不要将超时设置为仅5毫秒
您可以像下面这样更改togglePassword
功能,以在1000毫秒后切换输入以显示secreId:
我假设您正在将api返回的secred id存储在secredId
状态,因此我们只需要切换showId
状态
const togglePassword = () => {
this.setState({
showID: !this.state.showID,
}, () => {
setTimeout(() => {
this.setState({
showID: !this.state.showID,
});
}, 1000);
});
};
const HideID=“*******************”;为了帮助回应TJ关于5ms不够长的说法,请参见这一点,许多浏览器强制执行最小延迟,大多数情况下为4ms,因此尝试在5ms内调用回调几乎是可以延迟的最小延迟。100ms是一个更好的值,如果您四处搜索,您会发现许多库在200-250ms范围内更多地使用过渡/动画计时,因为这些对普通人眼来说更容易感知。
const togglePassword = () => {
this.setState({
showID: !this.state.showID,
}, () => {
setTimeout(() => {
this.setState({
showID: !this.state.showID,
});
}, 1000);
});
};