在功能组件中定义功能的最佳方法是什么?

问题描述 投票:0回答:2

关于在React.Component对象中定义函数的在线有很多指导,但我在查找功能组件中的函数的最佳实践时遇到了问题。例如,myFC_1与myMC_2在下面的打字稿代码中有什么含义。

interface Props { name: string};

export const myFC_1: FunctionComponent<Props> = (props:Props) {
    function helloWorld(): string {
        return "Hello " + props.name;
    }
    return <div> { helloWorld() }</div>
}

export const myFC_2: FunctionComponent<Props> = (props:Props) {
    const helloWorld =():string =>  {
        return "Hello " + props.name;
    } 
    return <div> { helloWorld() }</div>
}
reactjs typescript ecmascript-6 arrow-functions react-hooks
2个回答
1
投票

每次你这样做时都要保持一致..在功能组件中,使用哪种方法并不重要。胖箭可能有点慢,因为自动绑定在功能组件中是无用的,但我实际上只是猜测没有任何基准测试:)。

类组件是不同的东西。当你在render中定义函数时使用fat arrow,所以你不必考虑上下文绑定。因此,这里的主要任务是与您的团队交易您将使用的内容,然后遵循此规则。


0
投票

没有最好的方法,这是一个偏好的问题。

如有必要,功能声明可以从提升中受益:

export const myFC_1: FunctionComponent<Props> = (props:Props) {
    return <div> { helloWorld() }</div>

    function helloWorld() {
        return "Hello " + props.name;
    }
}

箭头功能可以是一个单行:

export const myFC_2: FunctionComponent<Props> = (props:Props) {
    const helloWorld =() => "Hello " + props.name;

    return <div> { helloWorld() }</div>
}

string类型是可选的,因为它是推断的。

© www.soinside.com 2019 - 2024. All rights reserved.