を作成し、私はボタンを押したときに、新しいメタはた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は将来ユーザーによって挿入されますが、現在のところ再レンダリングの動作をテストしています
問題は、関数を介してパラメータを渡さずにaddMeta内の変数を定義すると問題がありますメソッドがバインドされているかどうかをテストする)上記表示され、それは自分のアプリケーションのクラッシュに
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;
?それはonPressプロパティであるため、私はそれを押しても動かないはずですか?そして、なぜあなたの提案はうまくいくのですか?私の見解では、別の矢印で矢印の機能を呼び出す機能があります。 – Goamaral
'onPress = {this.addMeta( 'New Meta')}'はすべてのレンダリングで呼び出されます。 'onPress = {this.addMeta}'を実行すると、押されたときにのみ関数が呼び出されますが、パラメータを渡したいので、 'onPress = {() => this.addMeta( 'New Meta')} ' –