英文:
onPress never get fired when function is passed to it in react native?
问题
Here is the translated portion of the text you provided:
当我将函数传递给onPress
时,它从不被触发,只有当从子组件传递了对主组件中的函数的引用时才会触发。同时,即使我在TextInput
中输入值,它也返回没有值的警报。任何帮助将不胜感激。
例如,当我直接将props.onPress
传递给onPress
时,它被触发并调用引用函数。
<Button title='Add Goal' onPress={props.onPress} /> // 正常工作
但是,当我声明一个函数并将该函数传递给onPress
时,onPress
就像上面那样永远不会被触发。
以下是完整的代码:
function LoginKey(props) {
const [enteredApiKey, setEnteredKey] = useState('');
function keyInputHandler(enteredKey) {
setEnteredKey(enteredApiKey);
}
function Press() {
if (enteredApiKey.length === 0) {
Alert.alert('请输入一个值');
} else {
props.onPress();
}
}
return (
<Modal visible={props.visible} animationType='slide'>
<View style={styles.inputContainer}>
<Image
style={styles.image}
source={require('../assets/Image/ucp.png')}
/>
<TextInput
style={styles.textInput}
placeholder='输入 API 密钥!'
onChangeText={keyInputHandler}
/>
<View style={styles.buttonContainer}>
<Button title='Add Goal' onPress={Press} /> {/* 不起作用 */}
<Button title='Add Goal' onPress={props.onPress} /> {/* 起作用 */}
</View>
</View>
</Modal>
);
}
希望这有所帮助。
英文:
when I pass function to onPress it never gets fired and it only fires when the props with reference function from main component is passed from child component. AT the same time even if I enter value for usestate inside TextInput ,it returns Alert with no value. Any hep would he highly appreciated.
eg when I passed props.onPress directly to onPress, it gets fired and calls reference function.
<Button title='Add Goal' onPress={props.onPress} /> //WORKS
function Press() {
if(enteredApiKey.length()==""){
Alert.alert("enter a value ");
}
else {
props.onPress;
}
}
<Button title='Add Goal' onPress={Press} />. // NOT WORKING
but when I declare a function and pass that function to onPress , onPress never gets fired as above
Entire code is as below
function LoginKey(props) {
const [enteredApiKey, setEnteredKey] = useState('');
function keyInputHandler(enteredKey) {
setEnteredKey(enteredApiKey);
}
function Press() {
if(enteredApiKey.length()==""){
Alert.alert("enter a value ");
}
else {
props.onPress;
}
return (
<Modal visible={props.visible} animationType='slide'>
<View style={styles.inputContainer}>
<Image
style={styles.image}
source={require('../assets/Image/ucp.png')}
/>
<TextInput
style={styles.textInput}
placeholder='Enter Api key !'
onChangeText={keyInputHandler}
/>
<View style={styles.buttonContainer}>
<Button title='Add Goal' onPress={Press} /> // does not works
<Button title='Add Goal' onPress={props.onPress} />. //works
</View>
</View>
</Modal>
);
答案1
得分: 1
我尝试调用函数时没有在函数内使用(),即props.onpress()。
其次,我有一个拼写错误,我将false值作为参数输入。
英文:
I was trying to call function without () inside function ie props.onpress().
And secondly I have a typo error where I enter false value as argument
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论