Reactjs 在react功能组件中定义功能的最佳方法?
在线上有很多关于在React.Component对象中定义函数的指导,但我很难找到功能组件中函数的最佳实践。例如,在下面的typescript代码中,myFC_1和myMC_2的含义是什么Reactjs 在react功能组件中定义功能的最佳方法?,reactjs,typescript,ecmascript-6,arrow-functions,react-hooks,Reactjs,Typescript,Ecmascript 6,Arrow Functions,React Hooks,在线上有很多关于在React.Component对象中定义函数的指导,但我很难找到功能组件中函数的最佳实践。例如,在下面的typescript代码中,myFC_1和myMC_2的含义是什么 interface Props { name: string}; export const myFC_1: FunctionComponent<Props> = (props:Props) { function helloWorld(): string { return
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>
}
每次做这件事都要始终如一。。在功能组件中,使用哪种方法并不重要。Fat arrow可能会慢一点,因为自动绑定在功能组件中是无用的,但我只是猜测没有任何基准:
类组件是另一回事。。在render中定义函数时,请使用fat arrow,这样就不必考虑上下文绑定。因此,这里的主要问题是,只需与您的团队达成一致,然后遵循这条规则。没有最好的方法,这是一个偏好问题 如有必要,功能声明可受益于吊装:
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>
}
字符串类型是可选的,因为它是推断的。不同引擎的性能可能不同,但通常是相同的。