Получить название кнопки на пресс в реагировать родной
У меня есть две кнопки, которые обе вызывают одну и ту же функцию 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?
}
2 ответа
Решение
Одним из решений является передача этой информации в качестве параметра:
<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)}
/>
);
}
}
Чтобы повысить производительность, вы можете привязать обработчик событий в конструкторе, чтобы он отображался только один раз.
Подсказка Facebook (внизу страницы)
Мы обычно рекомендуем связывание в конструкторе или использование синтаксиса инициализатора свойства, чтобы избежать такого рода проблем с производительностью.
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>
);
}
}