Onpress没有调用函数来改变状态。

huangapple go评论103阅读模式
英文:

Onpress is not calling the function to change the state

问题

我正在使用React Native。我试图在按钮被点击时进行更改。我想要默认显示添加项目组件,当它被点击时,我想要将其更改为删除项目。

  1. const Products = () => {
  2. const [added, notAdd] = useState(false);
  3. function changeIT() {
  4. console.log(added);
  5. notAdd(!added);
  6. console.log(added);
  7. }
  8. return (
  9. {added ? <Remove index={index} onPress={() => changeIT()} /> : <Add item={item} onPress={() => changeIT()} />}
  10. );
  11. }

点击按钮后什么都没有发生。

英文:

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.

  1. const Products = () =&gt; {
  2. const [added,notAdd]=useState(false);
  3. function changeIT(){
  4. console.log(added);
  5. notAdd(!added);
  6. console.log(added);
  7. }
  8. return (
  9. {added?&lt;Remove index={index} onPress={()=&gt;changeIT()}/&gt; :&lt;Add item={item} onPress={()=&gt;changeIT()}/&gt; }
  10. )}

Nothing happens after I click on the buttons.

答案1

得分: 2

我相信您只包括了在组件执行时的onPress事件,而没有在实际组件本身中包括,例如。

执行:

  1. &lt;Add item={item} onPress={()=&gt;changeIT()}/&gt;

声明:

  1. import React, {useState} from &#39;react&#39;;
  2. import { Pressable, Text} from &#39;react-native&#39;;
  3. export default function Add({ item , onPress}) {
  4. return (
  5. &lt;Pressable onPress={onPress}&gt;
  6. &lt;Text&gt;Add&lt;/Text&gt;
  7. &lt;/Pressable&gt;
  8. );
  9. }
英文:

I believe you have only included the onPress event when the component is being executed, not in the actual component itself, for example.

Execution:

  1. &lt;Add item={item} onPress={()=&gt;changeIT()}/&gt;

Declaration:

  1. import React, {useState} from &#39;react&#39;;
  2. import { Pressable, Text} from &#39;react-native&#39;;
  3. export default function Add({ item , onPress}) {
  4. return (
  5. &lt;Pressable onPress={onPress}&gt;
  6. &lt;Text&gt;Add&lt;/Text&gt;
  7. &lt;/Pressable&gt;
  8. );
  9. }

huangapple
  • 本文由 发表于 2023年1月9日 19:20:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定