Javascript 为什么React方法不能按预期工作?

Javascript 为什么React方法不能按预期工作?,javascript,reactjs,typescript,react-native,Javascript,Reactjs,Typescript,React Native,我有一些代码是为了消除占位符onFocus并返回它们onBlur,它似乎可以正确地用于登录文本输入,但不适用于密码输入。你介意看一下代码吗 这就是所讨论的方法: togglePlaceholder=(节点类型:string,localStateValue:string)=>{ 开关(eval(`this.state.${localStateValue}`){ 案例节点类型: 返回此.setState({[localStateValue]:null}); 大小写为空: 返回此.setState({

我有一些代码是为了消除占位符onFocus并返回它们onBlur,它似乎可以正确地用于登录文本输入,但不适用于密码输入。你介意看一下代码吗

这就是所讨论的方法:

togglePlaceholder=(节点类型:string,localStateValue:string)=>{
开关(eval(`this.state.${localStateValue}`){
案例节点类型:
返回此.setState({[localStateValue]:null});
大小写为空:
返回此.setState({[localStateValue]:nodeType});
}
}
我在这里使用eval是因为我计划在多个组件之间重用这个函数来切换它们的本地状态

这些是组成部分:

<TextInput style={styles.logInFormInput}
    placeholder={this.state.logInPlaceholder}
    onFocus={()=>this.togglePlaceholder('login','logInPlaceholder')}
    onBlur={()=>this.togglePlaceholder('login','logInPlaceholder')}
></TextInput>

<TextInput style={styles.logInFormInput}
    secureTextEntry={true}
    placeholder={this.state.passwordPlaceholder}
    onFocus={()=>this.togglePlaceholder('password','passwordPlaceholder')}
    onBlur={()=>this.togglePlaceholder('password','passwordPlaceholder')}
></TextInput>
this.togglePlaceholder('login','logInPlaceholder')}
onBlur={()=>this.togglePlaceholder('login','logInPlaceholder')}
>
this.togglePlaceholder('password','passwordPlaceholder')}
onBlur={()=>this.togglePlaceholder('password','passwordPlaceholder')}
>

似乎可以正常登录,但不能使用密码。

考虑到您只是隐藏或显示,我认为您可以使用一种思维方式来轻松解决此问题:)

我认为最简单的方法是跟踪当前关注元素的id,并使用它有条件地呈现占位符:

<TextInput onFocus={() => setActive(id)} onBlur={clearActive} placeholder={this.state.activeId === id ? 'placeholder' : ''} />
setActive(id)}onBlur={clearActive}占位符={this.state.activeId===id?“占位符”:''}/>

创建一个HoC来管理其中的输入是很简单的,它允许您将其相应地分组

一条旁注,但是eval似乎是不必要的,而且令人困惑。为什么不
切换(this.state[localStateValue]){…
?您是否设置了一个断点以查看密码案例中实际发生的情况?使用自定义组件,您可以更轻松地实现这一点:(浏览器版本)如果您的状态
this.state={logInPlaceholder:“login”,passwordPlaceholder:“password”}
看起来像这样,应该可以正常工作!