Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - 为什么此React方法无法按预期工作?(Why is this React method not working as expected?)

I have some code that is meant to eliminate placeholders onFocus and return them onBlur, it seems to work properly for the login text input, but not for the password one.

(我有一些旨在消除占位符onFocus并将其返回给onBlur的代码,它似乎对于登录文本输入正确运行,但对于密码输入不是正确的。)

Do you mind having a look at the code?

(您介意看一下代码吗?)

This is the method in question:

(这是有问题的方法:)

togglePlaceholder = (nodeType:string,localStateValue:string) => {
    switch (eval(`this.state.${localStateValue}`)) {
        case nodeType:
            return this.setState({[localStateValue]:null});
        case null:
            return this.setState({[localStateValue]:nodeType});
    }
}

I'm using eval here because I'm planning to reuse this function across multiple components to toggle their local state.

(我在这里使用eval是因为我计划在多个组件之间重用此功能以切换其本地状态。)

These are the components:

(这些是组件:)

<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>

Seems to be working properly for login, but not password.

(似乎可以正常登录,但不能正常登录。)

  ask by OlegArsyonov translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given that you are just hiding or showing I think you could use a pivot of thinking to solve this a little easier :)

(鉴于您只是躲藏或展示,我认为您可以运用一些思路来解决这个问题:))

The simplest way in my mind to would be to track the id of the currently focused element and use it to conditionally render the placeholder:

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

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

It would be simple to create a HoC which manages the inputs within, allowing you to group it accordingly

(创建一个HoC来管理其中的输入将很简单,您可以据此对它进行分组)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...