我正在开发一个简单的计算器应用程序来学习本机反应。我有一个显示数字按钮的按钮组件。我需要向它传递一个函数,以便当触摸按钮时,父级的状态会更新为新数字。
如果没有bind(this),则表示this.setState未定义。当我在构造函数中添加绑定(this)时,我得到的只是应用程序中的空白页面。我的代码如下所示。
构造函数:
constructor() {
super();
this.state = {
total: 0,
display: 0
};
this._displayUpdate = this._displayUpdate.bind(this);
}
一排计算器按钮:
<View style={styles.buttonRow}>
<NumButton numText={7} update={this._displayUpdate} />
<NumButton numText={8} update={this._displayUpdate} />
<NumButton numText={9} update={this._displayUpdate} />
<FuncButton funcText={'*'} />
</View>
数字按钮组件:
export default class NumButton extends Component {
render() {
return (
<TouchableHighlight style={styles.buttonArea} onPress={this.props.update(this.props.numText)}>
<Text style={styles.buttonText}>{this.props.numText}</Text>
</TouchableHighlight>
)
}
}
你的父母bind
是对的。问题在于onPress
of the TouchableHighlight
in the NumButton
成分。您不能向其添加要执行的代码,您应该向其传递一个函数。您可以使用 ES6 箭头函数:
export default class NumButton extends Component {
render() {
return (
<TouchableHighlight style={styles.buttonArea}
onPress={()=>{ this.props.update(this.props.numText) }}
>
<Text style={styles.buttonText}>{this.props.numText}</Text>
</TouchableHighlight>
)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)