【问题标题】:react native : Create component to minimize lines of codereact native:创建组件以最小化代码行
【发布时间】:2021-11-08 02:18:55
【问题描述】:

在我的示例中,我尝试从以下代码创建一个名为 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 />

  )
}

【问题讨论】:

  • 您能否详细说明您的问题,提供更多详细信息以及错误日志(如果有)?
  • 我编辑我的问题。

标签: javascript reactjs react-native components jsx


【解决方案1】:

您的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 />
};

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

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

【讨论】:

  • 你是什么意思“将它移到主屏幕之外”。请用代码告诉我你是怎么做的,我所做的有什么不同?
  • 我已经在答案中添加了sn-p
  • 这可能是因为verifyNavigate()函数,你能发布错误日志试试评论onPress={() => verifyNavigate()}这一行
  • 不能在 MainScreen 内创建 nextButton 组件的组件内创建组件,因此它被视为普通函数而不是组件。
  • 您可以在我提供的单个文件示例 sn-p 中包含多个组件。您的 nextButton 版本位于 MainScreen 组件主体内。
猜你喜欢
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2017-06-22
相关资源
最近更新 更多