【问题标题】:Why is this React method not working as expected?为什么这个 React 方法没有按预期工作?
【发布时间】:2019-11-28 23:46:18
【问题描述】:

我有一些代码旨在消除占位符 onFocus 并将它们返回 onBlur,它似乎适用于登录文本输入,但不适用于密码输入。你介意看一下代码吗?

这是有问题的方法:

togglePlaceholder = (nodeType:string,localStateValue:string) => {
    switch (eval(`this.state.${localStateValue}`)) {
        case nodeType:
            return this.setState({[localStateValue]:null});
        case null:
            return this.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>

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

【问题讨论】:

  • 附注,但 eval 似乎没有必要且令人困惑。为什么不switch (this.state[localStateValue]) {...
  • 您是否设置了断点以查看密码情况下实际发生的情况?
  • 使用自定义组件,您可以更轻松地实现这一点:codesandbox.io/s/hopeful-moore-5oy6b(浏览器版本)
  • 如果您的状态 this.state = {logInPlaceholder: "login", passwordPlaceholder: "password"}; 看起来像这样,它应该可以正常工作!

标签: javascript reactjs typescript react-native


【解决方案1】:

鉴于您只是在隐藏或展示,我认为您可以使用思维支点来更轻松地解决这个问题:)

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

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

创建一个管理其中的输入的 HoC 会很简单,允许您对其进行相应的分组

【讨论】:

    猜你喜欢
    • 2014-12-24
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2020-07-24
    • 2011-11-20
    • 1970-01-01
    相关资源
    最近更新 更多