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

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

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 = () =&gt; {
const [added,notAdd]=useState(false);
 function changeIT(){
        console.log(added);
        notAdd(!added);
        console.log(added);
        
    }
return (
{added?&lt;Remove index={index} onPress={()=&gt;changeIT()}/&gt; :&lt;Add item={item} onPress={()=&gt;changeIT()}/&gt; }
)}

Nothing happens after I click on the buttons.

答案1

得分: 2

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

执行:

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

声明:

import React, {useState} from &#39;react&#39;;
import { Pressable, Text} from &#39;react-native&#39;;

export default function Add({ item , onPress}) {

  return (
    &lt;Pressable onPress={onPress}&gt; 
      &lt;Text&gt;Add&lt;/Text&gt;
    &lt;/Pressable&gt;
  );
}
英文:

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

Execution:

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

Declaration:

import React, {useState} from &#39;react&#39;;
import { Pressable, Text} from &#39;react-native&#39;;

export default function Add({ item , onPress}) {

  return (
    &lt;Pressable onPress={onPress}&gt; 
      &lt;Text&gt;Add&lt;/Text&gt;
    &lt;/Pressable&gt;
  );
}

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:

确定