How to bind(this) when passing a function as a pro

2020-07-28 11:19发布

问题:

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:

constructor() {
    super();
    this.state = {
      total: 0,
      display: 0
    };
    this._displayUpdate = this._displayUpdate.bind(this);
  }

One row of calculator buttons:

<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 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>
        )
    }
}

回答1:

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>
    )
}

}