英文:
Onpress is not calling the function to change the state
问题
我正在使用React Native。我试图在按钮被点击时进行更改。我想要默认显示添加项目组件,当它被点击时,我想要将其更改为删除项目。
const Products = () => {
const [added, notAdd] = useState(false);
function changeIT() {
console.log(added);
notAdd(!added);
console.log(added);
}
return (
{added ? <Remove index={index} onPress={() => changeIT()} /> : <Add item={item} onPress={() => changeIT()} />}
);
}
点击按钮后什么都没有发生。
英文:
I am using React Native.I am trying to change the button when it is clicked. I want to show the add item component by default and when it is clicked I want it to change to remove item.
const Products = () => {
const [added,notAdd]=useState(false);
function changeIT(){
console.log(added);
notAdd(!added);
console.log(added);
}
return (
{added?<Remove index={index} onPress={()=>changeIT()}/> :<Add item={item} onPress={()=>changeIT()}/> }
)}
Nothing happens after I click on the buttons.
答案1
得分: 2
我相信您只包括了在组件执行时的onPress
事件,而没有在实际组件本身中包括,例如。
执行:
<Add item={item} onPress={()=>changeIT()}/>
声明:
import React, {useState} from 'react';
import { Pressable, Text} from 'react-native';
export default function Add({ item , onPress}) {
return (
<Pressable onPress={onPress}>
<Text>Add</Text>
</Pressable>
);
}
英文:
I believe you have only included the onPress
event when the component is being executed, not in the actual component itself, for example.
Execution:
<Add item={item} onPress={()=>changeIT()}/>
Declaration:
import React, {useState} from 'react';
import { Pressable, Text} from 'react-native';
export default function Add({ item , onPress}) {
return (
<Pressable onPress={onPress}>
<Text>Add</Text>
</Pressable>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论