我已經這個組件具有一個簡單的按鈕,當我按下按鈕新的元應該被添加到顯示onPress與參數函數運行創建循環
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;
的paremeter的功能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;
它是如何執行addMeta?因爲它是一個onPress屬性不應該只在我按下它時運行?作爲一個小問題,你爲什麼會建議工作?在我看來,在另一個箭頭函數 – Goamaral
中調用箭頭函數onPress = {this.addMeta('New Meta')}'將在每個渲染上調用。當你執行'onPress = {this.addMeta}'時,它只會在按下時調用該函數,但由於你想傳遞一個參數,所以你可以創建一個匿名函數,只有在按下'onPress = { => this.addMeta('New Meta')}' –