我正在尝试创建登录表单,但出现此错误。
export default function LoginScreen(props) {
const [Submit, setSubmit] = React.useState('')
const windowWidth = Dimensions.get('window').width
const windowHeight = Dimensions.get('window').height
const [valuePass, setValuePass] = React.useState('')
const [valueUsername, setValueUsername] = React.useState('')
const [secureTextEntry, setSecureTextEntry] = React.useState(true)
const toggleSecureEntry = () => {
setSecureTextEntry(!secureTextEntry)
}
const AlertIcon = (props) => <Icon {...props} name='alert-circle-outline' />
const renderIcon = (props) => (
<TouchableWithoutFeedback onPress={toggleSecureEntry}>
<Icon {...props} name={secureTextEntry ? 'eye-off' : 'eye'} />
</TouchableWithoutFeedback>
)
return (
<View>
<Text>Login</Text>
<Input
placeholder='Username'
value={valueUsername}
style={{ width: windowWidth - 50, borderRadius: 16 }}
onChangeText={(nextValue) => setValueUsername(nextValue)}
size='large'
/>
<View style={{ height: 15 }}></View>
<Input
style={{ width: windowWidth - 50, borderRadius: 16 }}
size='large'
value={valuePass}
placeholder='Password'
caption='Should contain at least 8 symbols'
accessoryRight={renderIcon}
captionIcon={AlertIcon}
secureTextEntry={secureTextEntry}
onChangeText={(nextValue) => setValuePass(nextValue)}
/>
<View style={{ marginTop: 25 }}>
<Button
style={{ borderRadius: 15 }}
onPress={setSubmit(true)}
size='large'
>
Submit
</Button>
</View>
</View>
)
}
谁能解释为什么会出现这个错误??
我是 react-native 的新手。
忽略这个(只是为了增加音量)==我必须添加一些无用的句子,因为StackOverflow给了我'It looks like your post is mostly code; please add some more details.'
(对这个stackoverflow错误感到非常沮丧)
答案 0 :(得分:1)
对于按钮的 onPress 道具,您应该传递一个函数而不是直接传递一个实例。我的意思是这个;
<Button onPress={() => setSubmit(true)} />
对 <TouchableWithoutFeedback>
也这样做。
发生的事情是当组件安装时检查 onPress
并且在调用 setSubmit
时一次又一次地改变状态,但是当你传递一个函数时做这些事情,它等待点击,因为 onPress
需要在按下按钮时调用回调函数。
答案 1 :(得分:1)
问题出在你的 onPress 道具
onPress={setSubmit(true)}
花括号之间的所有内容都会立即计算。因此,在每个渲染循环中都会调用 setSubmit 函数。
通过用箭头函数包装函数,计算出的代码将生成一个函数,只要用户点击按钮就可以调用该函数。
应该是这样
onPress={()=>{setSubmit(true)}}