在React Native组件事件中定义和调用一个函数

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

Defining and calling a function in a React Native component event

问题

我有以下代码:

import { DraxView } from 'react-native-drax';

function MyComponent(props) {
   function test() { console.log('message') }
   const test2 = () => { console.log('message') }
   return (
     <DragView
      onDragDrop={console.log('message')}
     >
    </DragView>
   )
}

这段代码在每次事件发生时都会正确记录到控制台。但是,消息也会在第一次渲染MyView时记录。为了避免这种情况,我尝试替换为以下代码:

onDragDrop={test}

或者

onDragDrop={test2}

当事件发生时,这两者似乎都没有被调用,因为没有任何内容被记录到控制台。如何正确定义和调用这种方式的函数?

谢谢。

英文:

I have the following:

import { DraxView } from &#39;react-native-drax&#39;;

function MyComponent(props) {
   function test() { console.log(&#39;message&#39;) }
   const test2 = () =&gt; { console.log(&#39;message&#39;) }
   return (
     &lt;DragView
      onDragDrop={ console.log(&#39;message&#39;)}
     &gt;
    &lt;/DragView&gt;
   )
}

This correctly logs to the console every time the event occurs. However, the message is also logged the first time MyView is rendered. To avoid this, have tried replacing with the following:

onDragDrop={ test }

or

onDragDrop={ test2 }

Neither of these appear to be called, as nothing is logged when the event happens.

What is correct way to define and call a function in this way?

Thanks

答案1

得分: 1

onDragDrop={ console.log('message')} 在渲染过程中立即触发该函数,因为花括号内的表达式会立即执行。

所有这些选项都有效:

function test1() { console.log('test1') }
const test2 = () => { console.log('test2') }
return <>
  <Button title="TEST1" onPress={test1}/>
  <Button title="TEST2" onPress={test2}/>
  <Button title="TEST3" onPress={() => console.log('test3')}/>
</>;
英文:

onDragDrop={ console.log(&#39;message&#39;)} fires the function immediately during rendering, because expression inside the { } executes right away.

All these options works:

function test1() { console.log(&#39;test1&#39;) }
const test2 = () =&gt; { console.log(&#39;test2&#39;) }
return &lt;&gt;
  &lt;Button title=&quot;TEST1&quot; onPress={test1}/&gt;
  &lt;Button title=&quot;TEST2&quot; onPress={test2}/&gt;
  &lt;Button title=&quot;TEST3&quot; onPress={() =&gt; console.log(&#39;test3&#39;)}/&gt;
&lt;/&gt;

huangapple
  • 本文由 发表于 2023年7月18日 00:29:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706442.html
匿名

发表评论

匿名网友

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

确定