【发布时间】:2017-02-10 15:42:46
【问题描述】:
我有这个组件,它有一个简单的按钮,当我按下按钮时,一个新的 Meta 应该被添加到显示中
Metas.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import Meta from './Meta';
import Button from './Button';
class Metas extends Component {
componentWillMount() {
this.setState({
metas: this.props.data,
});
}
addMeta = (newMeta) => {
console.log('Adding new meta');
/*this.props.navigator.push({
id: 'Test'
});*/
const metas = this.state.metas;
metas.push(newMeta);
this.setState({ metas });
console.log(`Metas: ${metas}`);
}
renderData = () => {
console.log('rendering metas data');
return this.state.metas.map(meta => <Meta key={Math.random()} name={meta} />);
}
render() {
return (
<View>
{ this.renderData() }
<View>
<Text>{this.state.metas.length} Metas</Text>
<Button
text='+'
color='#8783FF'
fontColor='white'
size='50'
fontSize='25'
onPress={this.addMeta('New Meta')}
/>
</View>
</View>
);
}
}
export default Metas;
addMeta 函数的参数将来会由用户插入,但我目前只是测试重新渲染的工作原理
问题是,如果我不通过函数传递参数,并在 addMeta 中定义一个变量,它会完美运行(这样做是为了测试方法是否被绑定),但如果我按照上面显示的那样做,它会在onPress 属性甚至没有我点击它,导致我的应用程序崩溃
Button.js
import React, { Component } from 'react';
import { View, Text, TouchableNativeFeedback } from 'react-native';
class Button extends Component {
render() {
const { buttonStyle, centerHorizontally, textStyle } = styles;
const { text, onButtonPress } = this.props;
return (
<TouchableNativeFeedback onPress={onButtonPress}>
<View style={buttonStyle}>
<View style={centerHorizontally}>
<Text style={textStyle}>{text}</Text>
</View>
</View>
</TouchableNativeFeedback>
);
}
}
const styles = {
buttonStyle: {
borderRadius: 100,
justifyContent: 'space-around',
height: parseInt(this.props.size, 10),
width: parseInt(this.props.size, 10),
backgroundColor: this.props.color
},
/*TODO: use text align center instaed*/
centerHorizontally: {
flexDirection: 'row',
justifyContent: 'space-around'
},
textStyle: {
fontWeight: 'bold',
fontSize: parseInt(this.props.fontSize, 10),
lineHeight: parseInt(this.props.fontSize, 10)
+ Math.floor(parseInt(this.props.fontSize, 10) / 10) + 1,
color: this.props.fontColor
}
};
export default Button;
【问题讨论】:
标签: javascript reactjs react-native ecmascript-6