javascript - 样式不会传递给自定义组件 React Native

标签 javascript reactjs react-native components

我有一个带有此代码的自定义按钮组件

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/

相关文章:

javascript - Angular 4 : When and why is @Inject is used in constructor?

javascript - 当路由到具有不同参数的同一页面时,NextJS 初始状态不会更新

javascript - 如何在外部单击时关闭模态

javascript - 使用显示/隐藏通过 materliaze + react 重新排序 div 是个坏主意吗?

twitter-bootstrap - React.js 渲染与 Bootstrap 3 的差异

javascript - 单击时处理输入值 React js

javascript - React-Native 中更快的数组循环

android - 错误 : <identifier> expected with package com. native

javascript - React Native,在 for 循环中创建按钮

javascript - 如何向对话框添加div?