react native :创建组件以最小化代码行

react native : Create component to minimize lines of code

在我的示例中,我试图从以下代码创建一个名为 nextButton 的组件,然后我可以使用它。 我做的哪里有问题?


export const MainScreen = () => {

const nextButton =() => {
    return (
  <TouchableOpacity
          style={{ alignSelf: 'center' }}
          onPress={() => verifyNavigate()}
        >
          <LinearGradient
            colors={[Colors.Grayish_blue,
              Colors.Oval_blue,
              Colors.Dark_blue]}
            style={styles.linearGradientStyle}
          >
            <Text 
            style={styles.nextText}>next</Text>
          </LinearGradient>
        </TouchableOpacity>
         )
    }


return (
<nextButton />

  )
}

您的 nextButton 版本只是一个函数,而不是一个组件。 您不能在一个组件中创建一个组件,但您可以在一个文件中创建多个组件。

您可以在主屏幕中将其作为函数调用return

{nextButton()}

如果您想将它作为一个组件使用,您需要将它移到 MainScreen 组件主体之外

export const NextButton = () => {
  return (
    <TouchableOpacity
      style={{ alignSelf: "center" }}
      onPress={() => verifyNavigate()}
    >
      <LinearGradient
        colors={[Colors.Grayish_blue, Colors.Oval_blue, Colors.Dark_blue]}
        style={styles.linearGradientStyle}
      >
        <Text style={styles.nextText}>next</Text>
      </LinearGradient>
    </TouchableOpacity>
  );
};

export const MainScreen = () => {
  return <NextButton />
};

请记住,最佳做法是使用以大写字母开头的组件名称,因此将 nextButton 重命名为 NextButton

如果这对你有用,请为答案投票