在反应功能组件中定义功能的最佳方法?

时间:2019-04-08 16:25:29

标签: reactjs typescript ecmascript-6 arrow-functions react-hooks

在线上有很多关于在React.Component对象中定义函数的指导,但是我在寻找Functional Components中函数的最佳实践时遇到了麻烦。例如,下面的打字稿代码中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>
}

2 个答案:

答案 0 :(得分:1)

每次执行此操作时都必须保持一致。在功能组件中,它并不是真正使用的方法。胖箭头的速度可能会稍慢一些,因为自动绑定在功能组件中没有用,但是从字面上看,我只是猜测没有任何标记。类组件是另一回事。当您在render中定义函数时,请使用粗箭头,因此您不必考虑上下文绑定。因此,这里的主要目的是只与您的团队打交道,然后遵循此规则。

答案 1 :(得分: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类型是可选的,因为可以推断出它。