Get name of button onPress in react native

拥有回忆 提交于 2019-12-01 04:11:05

问题


I have two buttons that both call the same onPress function. In the callback I want to be able to differentiate between which was pressed.

<MKRadioButton
   title='A' 
   group={this.radioGroup}
   onPress={this._toggle}
 />

<MKRadioButton
   title='B' 
   group={this.radioGroup}
   onPress={this._toggle}
 />

then the call

_toggle(event) {
    //what should go here to figure out if title A or B was called?
}

回答1:


One solution is to pass that info as a parameter:

<MKRadioButton
  title='A' 
  group={this.radioGroup}
  onPress={(event) => this._toggle(event, 'A')}
/>

The callback would then use that parameter

_toggle(event, buttonId) {
  // Use buttonId
}

EDIT: Another solution is a parent component that always returns the title prop:

class RadioParent extends Component {
  render() {
    return (
      <MKRadioButton
        title={this.props.title} 
        group={this.props.radioGroup}
        onPress={(event) => this.props.onPress(event, this.props.title)}
      />
    );
  }
}



回答2:


To improve performance, you can bind the event handler in the constructor to have it rendered only once

Facebook tip (at the bottom of the page)

We generally recommend binding in the constructor or using the property initializer syntax, to avoid this sort of performance problem.

class MKRadioButtonWrapper extends React.PureComponent {
  constructor(props) {
    super(props);
    this.buttonPressed = this.buttonPressed.bind(this);
  }

  buttonPressed(){
    this.props.onPress(this.props.title);
  }

  render() {
    return (
    <MKRadioButton
       title={this.props.title}
       group={this.props.group}
       onPress={buttonPressed}
     />
    );
  }
}
class App extends React.Component {
  constructor(props) {
    super(props);

    this._toggle = this._toggle.bind(this);
  }

  _toggle(title) {
    //do what you want with the title
  }

  render() {
    return (
      <View>
        <MKRadioButtonWrapper
           title='A' 
           group={this.radioGroup}
           onPress={this._toggle}
         />

        <MKRadioButtonWrapper
           title='B' 
           group={this.radioGroup}
           onPress={this._toggle}
         />
      </View>
    );
  }
}


来源:https://stackoverflow.com/questions/44423132/get-name-of-button-onpress-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!