简体   繁体   中英

Too many re-renders. in React Native

I am making a custom TextInput component and in which i apply some different styles on the basis of state hook, which will be called onFocus and onBlur events, I've seen couple of solution on internet some of them are listed here Solution and i tried some of them but none of them work for me.

NOTE: I am using Expo.

Screen.js

import InputField from '../Components/InputField'

const Screen = () => {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    return(
         <InputField 
              placeholder='user@example.com' 
              label='E-mail' 
              value={email} 
              setValue={setEmail()} 
              isSecure={false}
              defState={false}/>
    )

}

InputField.js

const InputField = ({placeholder, label, value, setValue, isSecure, defState}) => {

    const [isFocused, setFocus] = useState(!!defState)
    const [isBlur, setBlur] = useState(!!defState)

    const handle_focus = () => {
        console.log('focused')
        setFocus(true)
        setBlur(false)
    } 

    const handle_blur = () => {
        console.log('blur')
        setBlur(true)
        setFocus(false)
    }

    return (
        <View style={isBlur ? styles.container : styles.focusContainer}>
            {isFocused ? <Text style={styles.label}>{label}</Text>: null}
            <View style={styles.inputCont}>
                <TextInput 
                    placeholder={placeholder}
                    secureTextEntry={isSecure}
                    value={value}
                    onChangeText={setValue}
                    onFocus={()=>handle_focus}
                    onBlur={()=>handle_blur}
                />
                <Icon name='checkmark-sharp' size={20} color={COLORS.blue} style={{marginLeft: 'auto'}}/>
            </View>
        </View>
    );
}

Error:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

In your InputField change this

onFocus={()=>handle_focus}
onBlur={()=>handle_blur}

To this

onFocus={() => handle_focus()}
onBlur={() => handle_blur()}

And also, in your Screen change this

setValue={setEmail()} 

to This

setValue={(text) => setEmail(text)} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM