React中用Styled Components包裹代码后,显示密码按钮功能异常
问题解决:包裹Styled Component后密码输入框内容消失
问题根源
你把StyledRegisterContainer和StyledButton这两个styled组件定义在了Register函数组件的内部。每次组件触发重新渲染(比如点击显示/隐藏密码按钮时),这两个组件都会被重新创建。React会将它们识别为全新的组件类型,因此会卸载原有的容器及内部表单元素,再重新挂载新的实例,直接导致密码输入框的内容丢失。
修复方案
将所有styled组件的定义移到Register组件的外部,确保组件类型在每次渲染时保持一致,避免不必要的DOM卸载和重建。
修改后的Register.js代码
import React from 'react' import Styled from "styled-components"; // 将styled组件移到组件外部 const StyledButton = Styled.button` background-color: ${(props)=>props.bgColor}; color: white; display:${(props)=>props.flag==="1"?"inline-block":"block"}; width:${(props)=>props.flag==="1"?"45%":"100%"}; margin:5px; `; const StyledRegisterContainer = Styled.div` width:600px; &:hover {box-shadow:0px 0px 5px grey}; @media (min-width:0px) and (max-width:600px) { width:300px; }; `; export default function Register(props) { const btnStyle={ backgroundColor:"red", color:"white", } let btnText; const btnClasses = ["btn","m-1","mt-2"]; if(props.showPass===true) { btnStyle.backgroundColor = "green"; btnText="hide password"; btnClasses.push("btn-primary"); } else{ btnText="show password"; btnClasses.push("btn-danger"); } return ( <StyledRegisterContainer className='container card mt-4 p-3 '> <h1 className='text-center'> Registration Form </h1> <form onSubmit={props.submit}> <div className='form-group'> <label className='control-label' htmlFor='name'>Name:</label> <input type='text' name='name' className='form-control'/> </div> <div className='form-group'> <label className='control-label' htmlFor='email'>Email:</label> <input type='email' name='email' className='form-control'/> </div> <div className='form-group'> <label className='control-label' htmlFor='password'>password:</label> <input type={props.showPass?"text":"password"} name='password' required className='form-control' /> </div> <button type='submit' className='btn btn-primary mt-2 m-1'> Register </button> <button type ="button" className={btnClasses.join(" ")} onClick={props.click}> {btnText} </button> <br/> <StyledButton flag="1" bgColor="orange">Login</StyledButton> <StyledButton flag="1" bgColor="blue">Login</StyledButton> <StyledButton flag="0" bgColor="brown">Login</StyledButton> </form> </StyledRegisterContainer> ) }
内容的提问来源于stack exchange,提问作者Hamad Ur Rehman
相关产品推荐
相关产品推荐

