react-native - 我构建了自己的按钮组件,但无法正常工作
问题描述
我使用 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>
);
}
}
我可以按下按钮,但控制台窗口上没有显示任何内容。
解决方案
你做的按钮中没有箭头函数,使用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>
推荐阅读
- reactjs - 如何在 React 中对 Office UI Fabric 表单进行无浏览器测试
- c# - 将带有GMT的字符串中的DateTime转换为C#中的本地时间
- java - Hbase中的Apache Phoenix日期字段查询
- sql-server - 返回表单后 DataCombo 未刷新
- maven - 如何将 pom 设置为 maven 插件中的默认工件?
- php - Cakephp 3.6:从表单获取数据 - 奇怪的解决方法
- asp.net - targetFramework-Attribute... 更高版本 4
- asp.net-core-2.1 - .net core 2.1 基于声明的身份验证
- xml - 基于元素值(包括子实体)组合 XML 消息
- haskell - haskell - 无法将类型“(Char,Int)”与“[Char]”错误匹配