javascript - 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 />
)
}
解决方案
您的版本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
.
如果这对您有用,请为答案投票
推荐阅读
- python - 类型错误:__init__() 缺少 1 个必需的位置参数:临时邮件 python 中的“api_key”
- reactjs - 如何将“strinsert”自定义下拉插件添加到 ckeditor4-react?
- python - 自动包装/装饰所有 pytest 单元测试
- laravel - 如何在 My Laravel Vue 项目中获取多个关系数据
- javascript - 如何从谷歌云应用引擎与外部 exe 程序通信?
- php - FPDF在一个单元格中设置2个连续值
- typescript - “TS7030:并非所有代码路径都返回值”与 ESLint “no-undefined”和“no-useless return”冲突解决
- python - 使用泊松似然的 GP 回归
- c# - 实体框架核心
- android - 无法将列表转换为 Kotlin 中的特定数据类到 %Class%