Не могу получить правильное значение состояния - PullRequest
0 голосов
/ 28 октября 2019

Я новичок в реакции-родной. Я пытаюсь создать группу кнопок, которая работает как радиокнопки.
ButtonsGroup отображается правильно, но я получаю неверный selectedIndex из App.js. Когда я выбираю вторую кнопку, я получаю выбор индекса 0 вместо 1.

ButtonsGroup .js

import React, {Component} from 'react';
import {View, Text, TouchableNativeFeedback} from 'react-native';

export default class ButtonsGroup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedIndex: this.props.selectedIndex,
      buttons: this.props.buttons,
    };
  }

  _updateIndex = index => {
    this.setState({selectedIndex: index});
    this.props.onPress(this.state.selectedIndex);
  };

  _renderButtons() {
    const buttons = this.state.buttons.map((title, index) => {
      return (
        <View
          key={index}
          style={{
            height: this.props.height,
            backgroundColor: 'transparent',
            flex: 1,
            borderRadius: 18,
            elevation: 2,
            marginRight: index < this.state.buttons.length - 1 ? 10 : 0,
          }}>
          <TouchableNativeFeedback
            background={TouchableNativeFeedback.Ripple('dark', true)}
            onPress={() => this._updateIndex(index)}>
            <View
              style={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor:
                  this.state.selectedIndex == index ? '#2566d4' : 'white',
              }}>
              <Text
                style={{
                  color: this.state.selectedIndex == index ? 'white' : 'black',
                }}>
                {title}
              </Text>
            </View>
          </TouchableNativeFeedback>
        </View>
      );
    });

    return buttons;
  }

  render() {
    console.log(this.props);
    return (
      <View style={{...this.props.style, flexDirection: 'row'}}>
        {this._renderButtons()}
      </View>
    );
  }
}

App.js

import React, {Component} from 'react';
import {View} from 'react-native';
import ButtonsGroup from './components/ButtonsGroup';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedIndex: 0,
    };
    this._updateIndex = this._updateIndex.bind(this);
  }

  _updateIndex(selectedIndex) {
    this.setState({selectedIndex:selectedIndex});
  }

  render() {
    const {selectedIndex} = this.state;
    return (
        <View>
          <ButtonsGroup
            onPress={this._updateIndex}
            buttons={['button1', 'button2']}
            selectedIndex={selectedIndex}
            height={38}
            style={{margin: 10}}
          />
        </View>
    );
  }
}

Не предлагать GroupButton из'act-native-elements '.

1 Ответ

0 голосов
/ 28 октября 2019

вы используете this.state.selectedIndex немедленно

_updateIndex = index => {
  this.setState({selectedIndex: index});
  this.props.onPress(this.state.selectedIndex);
};

вы должны использовать

_updateIndex = index => {
    this.setState({selectedIndex: index});
    this.props.onPress(index);
 };
...