我有一个带有此代码的自定义按钮组件
import React from 'react';
import { TouchableOpacity, View, Text } from 'react-native';
import PropTypes from 'prop-types';
import styles from './styles';
const CustomBtn = ({props, text, onPress }) => (
<TouchableOpacity {...props} onPress={onPress}>
<View style={styles.button}>
<Text style={styles.text}>{text}</Text>
</View>
</TouchableOpacity>
);
CustomBtn = {
text: PropTypes.string,
onPress: PropTypes.func,
};
export default CustomBtn;
我想在我编写的 View 中覆盖组件的样式(边距、填充)
<CustomBtn style={styles.BtnMargin} onPress={this.handlePressLogin} text="Login" />
但是我的自定义 Button 没有得到样式。如何更改自定义 btn 的代码来解决这个问题?
最佳答案
您正在使用 stateless component错误的。如果您查看签名,您会注意到它接受 props 作为参数:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
在行 {...props}
varibale props
是未定义的,因为它与 this.props.props
相同正常组件。你真正想做的是:
const CustomBtn = (props) => (
<TouchableOpacity {...props} onPress={props.onPress}>
<View style={styles.button}>
<Text style={styles.text}>{props.text}</Text>
</View>
</TouchableOpacity>
);
关于javascript - 样式不会传递给自定义组件 React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47551555/