介绍
我有这个密码:
import React, { Component } from 'react';
import { View, Button } from 'react-native';
export default function App() {
const myMethod = (name) => {
console.log(`Hello ${name}!`);
};
return (
<View>
<Button onPress={() => myMethod("Victor")}>
Press me!
</Button>
</View>
);
}
然后,我决定用curried函数重构它.这样地:
import React, { Component } from 'react';
import { View, Button } from 'react-native';
export default function App() {
/**
* @param {string} name - The name.
* @returns {Function} Curried function.
*/
const myMethod = (name) => {
return () => {
console.log(`Hello ${name}!`);
}
};
return (
<View>
<Button onPress={myMethod("Victor")}>
Press me!
</Button>
</View>
);
}
如您所见,我调用该方法的方式已经改变,因为我返回的是一个函数,而不是myMethod
中的void
.这很酷,很有效...每次按下按钮,就会调用我的方法.
判断这小吃:https://snack.expo.dev/Rx3iBVT_W
问题
现在,我试图用curry
from Lodash来重构重构代码.
这就是我try 过的:
import React, { Component } from 'react';
import { View, Button } from 'react-native';
import { curry } from 'lodash';
export default function App() {
const myMethod = curry((name) => {
console.log(`Hello ${name}!`);
});
return (
<View>
<Button onPress={myMethod("Victor")}>
Press me!
</Button>
</View>
);
}
但出于某种原因,这是行不通的.该方法不会在每次按下按钮时执行...相反,它在组件装载时被调用.
我该怎么解决呢?