我在react native中制作了一个自定义Button(component),以便在整个应用程序中使用所需的参数值(颜色,标题,onPress功能等),但是它不接受这些值,我正在继续调用
这是我的按钮类
import React from 'react';
import {Button,Text} from 'react-native';
export const CustomButton = ({btnTitle, btnBgColor,btnPress}) =>
(
<Button
title={btnTitle}
style={
{
width:'200',
height:'40',
padding:10,
marginTop:20,
backgroundColor:'btnBgColor',
}}
onPress = {btnPress}>
</Button>
);
我在这里使用它
export class Login extends Component<Props> {
render() {
return(
<View style={styles.containerStyle}>
<ImageBackground source={require ('./../../assets/images/bg.jpg')}
style={styles.bgStyle}/>
<View style={styles.loginAreaViewStyle}>
<Image />
<CustomInputField
inputPlaceholder={'Email'}
userChoice_TrF={false}
/>
<CustomInputField
inputPlaceholder={'Password'}
userChoice_TrF={true}
/>
<CustomButton
btnTitle={'Login'}
btnBgColor={'black'}
btnPress={this._LoginFunction()}/>
</View>
</View>
);
}
_LoginFunction()
{
return(alert('Login successful'))
}}
您可以看到我的参数值,颜色,宽度,高度等对按钮没有影响
答案 0 :(得分:2)
问题是因为您基本上已经围绕Button
的{{1}}组件创建了一个包装器
https://facebook.github.io/react-native/docs/button
如果您查看按钮的文档,则只能使用7个道具 https://facebook.github.io/react-native/docs/button#props
- onPress
- 标题
- accessibilityLabel
- 颜色
- 已禁用
- testID
- 具有TVPreferredFocus
没有react-native
道具。因此,您传递的内容将被忽略。
您需要在style
中使用CustomButton
之一
https://facebook.github.io/react-native/docs/handling-touches#touchables
所以您的组件可能会变成这样(您可能需要调整样式等):
Touchables
此外,您需要为import React from 'react';
import {TouchableOpacity,Text} from 'react-native';
export const CustomButton = ({btnTitle, btnBgColor,btnPress}) =>
(
<TouchableOpacity
style={{
width:200,
height:40,
padding:10,
marginTop:20,
backgroundColor:{btnBgColor},
}}
onPress = {btnPress}>
<Text>{btnTitle}</Text>
</TouchableOpacity>
);
和width
传递的值必须是数字。
这是一款可以https://snack.expo.io/@andypandy/custom-button-example工作的小吃
答案 1 :(得分:1)
使用这种箭头功能
看到差异
export const CustomButton = ({btnTitle, textColor, textSize, btnBgColor, btnPress}) =>
({
<Button
title={btnTitle}
style={{
width:'200',
height:'40',
padding:10,
marginTop:20,
backgroundColor:{btnBgColor},
}}
onPress = {btnPress}>
</Button>
});
<CustomButton
btnTitle='login'
btnBgColor='black'
btnPress={this._LoginFunction()}
/>
答案 2 :(得分:1)
在这里,我对您的代码进行了一些更改。
import React from "react";
import {TouchableOpacity,Text} from 'react-native';
export const AppButton = ({btnTitle, btnBgColor, textColor, btnTextSize, btnPress, btnPadding})=>(
<TouchableOpacity style={{backgroundColor:btnBgColor }} onPress={btnPress}>
<Text style={{color:textColor, fontSize:btnTextSize, padding: btnPadding}}>
{btnTitle}
</Text>
</TouchableOpacity>
)
像这样使用它,绝对可以解决您的问题。
import {AppButton} from "../../components/AppButton";
<AppButton
btnBgColor={'#2abec7'}
btnPadding={10}
btnPress={this._LoginFunction}
btnTextSize={18}
btnTitle={'list'}
textColor={'#000'}
/>
并且不要在
使用()
btnPress={this._LoginFunction()}
只需将其用作
btnPress={this._LoginFunction}