React Native 不尊重函数范围

React Native doesn't respect the function scope

提问人:Ashish 提问时间:9/22/2023 更新时间:9/22/2023 访问量:38

问:

我正在开发一个 react-native 应用程序。 最近,我遇到了功能组件的奇怪行为。通常,我会将大型组件分解为较小的组件,为每个较小的组件编写单独的逻辑,然后在同一组件中调用它们。

在下面的代码中,我没有定义该方法,但是当我单击它时,它会从onPressedSmallComponentBSmallComponentA

const SmallComponentA = ({}) => {

    onPressed = () => alert('Clicked A')

    return <Text onPress={onPressed} >Press On A</Text>
}

const SmallComponentB = ({}) => {
    return <Text onPress={onPressed} >Press On B</Text>
}

const ActualComponent = ({}) => {
    return(
        <>
        <SmallComponentA />
        <SmallComponentB />
        </>
    )
}
reactjs react-native react-functional-component

评论

1赞 Ruan Mendes 9/22/2023
这是因为您正在创建一个全局变量。您必须使用马虎模式(而不是严格模式)。更改代码,你将获得预期的行为。const onPressed = () => alert('Clicked A')
0赞 Ashish 9/22/2023
@RuanMendes 是的,它有效。谢谢!

答:

-1赞 Bala Vigness 9/22/2023 #1

因此,您可以在每个单独的箭头函数中单独设置 onPressed 函数,例如,

const SmallComponentA = ({}) => {
    const onPressed = () => alert('Clicked A');

    return <Text onPress={onPressed}>Press On A</Text>;
}

const SmallComponentB = ({}) => {
    const onPressed = () => alert('Clicked B');

    return <Text onPress={onPressed}>Press On B</Text>;
}

const ActualComponent = ({}) => {
    return (
        <>
            <SmallComponentA />
            <SmallComponentB />
        </>
    );
}

-1赞 Nensi Kasundra 9/22/2023 #2

你可以用两种方式来做,要么它是一个单独的函数,要么它应该是一个通用的函数

与分离:

    const SmallComponentA = ({}) => {
        const onPressed = () => alert('Clicked A')
    
        return <Text onPress={onPressed} >Press On A</Text>
    }
    
    const SmallComponentB = ({}) => {
        const onPressed = () => alert('Clicked B')
    
        return <Text onPress={onPressed} >Press On B</Text>
    }
    
    const ActualComponent = ({}) => {
        return(
            <>
            <SmallComponentA />
            <SmallComponentB />
            </>
        )
    }

常用功能:

    const onPressed = ( component ) => alert('Common Clicked '+ component);
    
    const SmallComponentA = ({}) => {
      return <Text onPress={()=>onPressed("A")}>Press On A</Text>;
    };
    
    const SmallComponentB = ({}) => {
      return <Text onPress={()=>onPressed("B")}>Press On B</Text>;
    };
    
    const ActualComponent = ({}) => {
      return (
        <>
          <SmallComponentA />
          <SmallComponentB />
        </>
      );
    };

希望它能让你满意!

评论

1赞 Ashish 9/22/2023
是的,通过添加 const 关键字,它可以正常工作。对于您的第二种方法 - 我们应该避免在 render 方法中使用箭头函数,因为箭头函数每次都会返回一个新函数。这导致 React 认为在我们看来有些东西发生了变化,而实际上什么都没有改变。