【问题标题】:Get name of button onPress in react native在本机反应中获取按钮onPress的名称
【发布时间】:2017-11-09 10:13:01
【问题描述】:

我有两个按钮,它们都调用相同的 onPress 函数。在回调中,我希望能够区分被按下的。

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

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

然后调用

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

【问题讨论】:

    标签: button react-native onpress


    【解决方案1】:

    一种解决方案是将该信息作为参数传递:

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

    回调将使用该参数

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

    编辑: 另一种解决方案是父组件总是返回标题属性:

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

    【讨论】:

    • 我不知道你的意思是什么,你指的是 title 属性是 A 以及回调参数吗?您要完成的问题中是否还有其他未说明的内容?
    • 是的,我有 30 个这样的按钮,所以必须有很多额外的文本,而且以后很难更新。理想情况下,我想获得对被点击按钮的引用并以这种方式找到标题
    • 你可以通过创建一个父组件来解决这个问题(如果扩展MKRadioButton的API不是一个选项),它总是返回给定的title prop作为onPress中的第二个参数,类似于上面的代码。
    • 添加了一个父组件的例子。这符合您的要求吗?
    【解决方案2】:

    为了提高性能,您可以在构造函数中绑定事件处理程序,使其仅呈现一次

    Facebook tip(在页面底部)

    我们通常建议在构造函数中绑定或使用属性初始化语法,以避免此类性能问题。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2018-06-03
      • 2018-06-03
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      相关资源
      最近更新 更多