为所有输入类型创建通用文本框

由于我是 React JS 的新手,我需要支持为所有输入类型创建一个通用文本框。此外,我已经开发了文本框,但是当类型为密码时,我需要显示密码功能。但是,目前,当我第一次单击它时,我的显示密码元素消失了。


import React, { useState, useEffect } from 'react';

const TextBox=(props)=> {

const [type, setType] = useState('text');

const [placeholder, setPlaceholder] = useState('Text');

const [passValue, setPassValue] = useState();

useEffect(() => {

    setType(props.type);

    setPlaceholder(props.placeholder);

}, []);


const handleChange=(e)=>{

    setPassValue(e.target.value);

}


const showHide=(e)=>{

    e.preventDefault();

    e.stopPropagation();

    setType(type === 'input' ? 'password' : 'input') 

}


return (

    <div>

    <h1>{type}:{placeholder}</h1>

    <input type={type} placeholder={placeholder} onChange={handleChange}></input>

    {(type==='password', type=== 'input') && 

        <div>

            <p>This is Password</p>

                <span onClick={showHide}>{type === 'input' ? 'Hide' : 'Show'}</span>

        </div>

    }

    {(type==='text')&&<p>This is Text</p>}

    {(type==='email')&&<p>This is an Email</p>}

    </div>

);

}

export default TextBox;

我的道具正在通过以下代码获取:


<TextBox type="password" placeholder="Enter your Password"/>

如何在左侧的输入文本中显示显示/隐藏,并保留上述代码?


<input class='container textContainer' type={type} placeholder={placeholder} onChange={handleChange} /> 

{(type==='password' || type=== 'input') && 

<span onClick={showHide}> 

    {type === 'input' ? 'Hide' : 'Show'} 

</span> }


繁花不似锦
浏览 137回答 3
3回答

萧十郎

将您的密码条件更改为以下代码&nbsp; {(type==='password' || type=== 'input') &&&nbsp;&nbsp; <div>&nbsp; &nbsp; <p>This is Password</p>&nbsp; &nbsp; &nbsp; <span onClick={showHide}>&nbsp; &nbsp; &nbsp; &nbsp; {type === 'input' ? 'Hide' : 'Show'}&nbsp; &nbsp; &nbsp; </span>&nbsp; </div>}

噜噜哒

您处理有关何时显示元素的条件的方式使应用程序崩溃。此外,您可能需要重新考虑使用它useEffect并允许对组件进行更多控制。您不需要将type和placeholder道具保存到状态,删除它会稍微简化您的代码。function TextBox({ type, placeholder }) {&nbsp; const [ value, setValue ] = useState('');&nbsp; const [ visible, setVisible ] = useState(false);&nbsp; const handleChange = (e) => setValue(e.target.value);&nbsp; const showhide = () => setVisible(visible => !visible);&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <h1>{type}:{placeholder}</h1>&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; value={value}&nbsp; &nbsp; &nbsp; &nbsp; type={type}&nbsp; &nbsp; &nbsp; &nbsp; placeholder={placeholder}&nbsp; &nbsp; &nbsp; &nbsp; onChange={handleChange}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; {type === 'password' && (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>This is Password <button onClick={showhide}>Show/Hide</button></p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {visible && <span>{value}</span>}&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; &nbsp; {type==='text' && <p>This is Text</p>}&nbsp; &nbsp; &nbsp; {type==='email' && <p>This is an Email</p>}&nbsp; &nbsp; </div>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript