在 React Native 中将函数作为道具传递时如何绑定(this) [英] How to bind(this) when passing a function as a prop in react native
问题描述
我正在开发一个简单的计算器应用程序来学习 React Native.我有一个显示数字按钮的按钮组件.我需要向它传递一个函数,以便在触摸按钮时父项的状态更新为新数字.如果没有 bind(this) 它说 this.setState 是未定义的.当我在构造函数中添加 bind(this) 时,我得到的只是我的应用程序中的一个空白页面.下面列出了我的代码.
I am working on a simple calculator app to learn react native. I have a button component that displays the number buttons. I need to pass it a function so that when the button is touched the state of the parent is updated to the new number. Without the bind(this) it says this.setState is undefined. When I add bind(this) in the constructor all I get is a blank page in my app. My code is listed below.
构造函数:
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>
NumButton 组件:
NumButton Component:
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
是对的.问题在于 NumButton
组件中 TouchableHighlight
的 onPress
.您不能向它添加要执行的代码,您应该向它传递一个函数.你可以使用 ES6 箭头函数:
Your parent bind
is right. The problem is with the onPress
of the TouchableHighlight
in the NumButton
component. You can't add code to execute to it, You should pass a function to it. You can use ES6 arrow function:
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>
)
}
}
这篇关于在 React Native 中将函数作为道具传递时如何绑定(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!