0

我使用 React Native 构建了自己的按钮组件,并尝试在我的代码中使用它。我现在要做的就是让它记录控制台消息,但由于某种原因它没有这样做。

按钮组件

import React, {Component} from 'react';
import { Text, TouchableOpacity } from 'react-native';

class Button extends Component {
  render(){
    const { onPress, children } = this.props;
    const { buttonStyle, textStyle } = styles;

    return (
      <TouchableOpacity onPress={ onPress } style={ buttonStyle }>
        <Text style={ textStyle }>
          { children }
        </Text>
      </TouchableOpacity>
    );
  }
}

使用按钮的代码

class FlashcardMenuDetail extends Component {
  onButtonPress() {
    console.log('You pushed the button');
  }

  render() {
    const { title } = this.props.flashcard;

    return (
      <Card>
        <CardItem>
          <Button onpress={this.onButtonPress.bind(this)}>
            { title }
          </Button>
        </CardItem>
      </Card>
    );
  }
}

我可以按下按钮,但控制台窗口上没有显示任何内容。

4

1 回答 1

0

你做的按钮中没有箭头函数,使用onPress函数的函数时,只留下控制台日志,因为返回值是导入的。您必须添加箭头功能。

export const makeButton = (props) => {
    const { title = "title", buttonStyle = {}, textStyle = {}, onPress } = props;

    return (
        <TouchableOpacity onPress={() => onPress} style={buttonStyle}>
            <Text style={textStyle}>{props.title}</Text>
        </TouchableOpacity>
    );
};

用法

import { makeButton } from 'path/makeButton.js';


      <Card>
        <CardItem>
         <makeButton
            title="get console.log"
            onPress={() => onButtonPress() }
            buttonStyle ={{ /* some styles for button */ }}
            textStyle={{ /* styles for button title */ }}
        />
        </CardItem>
      </Card>
于 2019-08-02T17:15:45.327 回答