英文:
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 'react-native-drax';
function MyComponent(props) {
function test() { console.log('message') }
const test2 = () => { console.log('message') }
return (
<DragView
onDragDrop={ console.log('message')}
>
</DragView>
)
}
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('message')}
fires the function immediately during rendering, because expression inside the { }
executes right away.
All these options works:
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')}/>
</>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论