案例1:文件范围全局函数
// test.tsx
const someFunction = (text) => {
console.log(text)
}
class SomeComponent extends React.Component {
constructor(props){
super(props)
someFunction("Hello World!")
}
}
案例2:类方法
// test2.tsx
class SomeComponent extends React.Component {
constructor(props){
super(props)
this.someFunction("Hello World!")
}
someFunction(text){
console.log(text)
}
}
在函数组件中,每次渲染都会重新创建函数,因此可以使用useCallback
对其进行优化,但据我所知,类组件的方法并非如此。
除了case 1
中的someFunction
不能访问this
之外,这两种方法有什么不同吗?
我认为这最终是你的选择,但我个人更喜欢只将函数放在类中,这样每当我继承一个类时,所有函数都可以在另一个类中使用(另外,这并不重要(
像这个
class SomeComponent extends React.Component {
helloWorld(number){
return number + 2;
}
}
和
class AnotherComponent extends SomeComponent {
render(){
<div onClick ={()=>{
helloWorld(10)}}>
</div>
}
}
另一方面,如果在类之外定义函数,则可以直接导出函数
export const someFunction = (text) => {
console.log(text)
}
class SomeComponent extends React.Component {
constructor(props){
super(props)
someFunction("Hello World!")
}
}