首页 > 解决方案 > react native:创建组件以最小化代码行

问题描述

在我的示例中,我试图创建一个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 />

  )
}

标签: javascriptreactjsreact-nativecomponentsjsx

解决方案


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

您可以在 MainScreen 返回中将其作为函数调用

{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 />
};

请记住最佳实践是使用以大写字母开头的组件名称,因此重命名nextButtonNextButton.

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


推荐阅读