Реагируйте: кнопка не работает (onClick) - должна быть передана в index.js, но ничего не происходит - PullRequest
0 голосов
/ 26 июня 2019

Я написал следующий веб-сайт: https://konekto -571cnq6xu.now.sh / emergency_details1 Если вы быстро щелкнете по настройке и настройке, вы увидите, что у меня есть один "Кого вы хотитесвязаться?»экран.Однако, если вы нажмете кнопку со стрелкой внизу, ничего не произойдет, и вы не будете перенаправлены, даже если функция handleDetails2 () позаботится об этом.Здесь вы можете увидеть класс относительно этого (FormEmergencyType):

import React from 'react';
import { IconButton, Grid, Typography } from '@material-ui/core';
import ArrowForward from '@material-ui/icons/ArrowForward';
import { withStyles } from '@material-ui/core/styles';
import CheckBoxGroup from '../utils/CheckBoxGroup';
import CheckBox from '../utils/CheckBox';
//import SOSButton from './SOSButton';

const styles = theme => ({
  container: {
    alignItems: 'center',
    // background: 'white',
    border: 'black',
    'border-width': 'medium',
    'margin-top': '80px',
    background: 'rgba(255, 255, 255, 0.8)',
    'border-radius': '20px'
  },
  item: {
    // background: 'red',
    width: '100%',
    //background: 'white',
    'text-align': 'center',
    'border-radius': '5px',
    'margin-top': '10px'
  },
  label: {
    // background: 'white'
  }
  // forwardbutton: {
  //   'text-align': 'right'
  // }
});

class FormEmergencyType extends React.Component {
  //const classes = useStyles(); //React HOOK API => looks nice
  constructor(props) {
    super(props);
    //const { classes } = props;
    this.classes = props.classes;
    this.state = {
      ambulance: props.emergencyTypes.ambulance,
      fire_service: props.emergencyTypes.fire_service,
      car_service: props.emergencyTypes.car_service,
      police: props.emergencyTypes.police,
      emergency_contacts: props.emergencyTypes.emergency_contacts
    };

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

  handleChange(event, checked) {
    let new_state = this.state;

    switch (event.target.value) {
      case 'ambulance':
        new_state['ambulance'] = checked;
        break;
      case 'fire_service':
        new_state['fire_service'] = checked;
        break;
      case 'police':
        // new_state['emergencytype']['police'] = checked;
        new_state['police'] = checked;
        break;
      case 'car_service':
        // new_state['emergencytype']['car_service'] = checked;
        new_state['car_service'] = checked;
        break;
      case 'emergency_contacts':
        // new_state['emergencytype']['car_service'] = checked;
        new_state['emergency_contacts'] = checked;
        break;
      default:
        break;
    }

    this.setState(new_state);
    this.props.handleEmergencyType(new_state);
  }

  render() {
    return (
      <Grid
        container
        className={this.classes.container}
        direction="column"
        spacing={2}
      >
        <Grid item sm={12} className={this.classes.item}>
          <Typography variant="h5">Who do you want to contact?</Typography>
          <CheckBoxGroup>
            <CheckBox
              title="Ambulance"
              onChange={this.handleChange}
              checked={this.state['ambulance']}
              value="ambulance"
            />
            <CheckBox
              title="Fire Service"
              onChange={this.handleChange}
              checked={this.state['fire_service']}
              value="fire_service"
            />
            <CheckBox
              title="Police"
              onChange={this.handleChange}
              checked={this.state['police']}
              value="police"
            />
            <CheckBox
              title="Car Service"
              onChange={this.handleChange}
              checked={this.state['car_service']}
              value="car_service"
            />
            <CheckBox
              title="Emergency Contacts"
              onChange={this.handleChange}
              checked={this.state['emergency_contacts']}
              value="emergency_contacts"
            />
          </CheckBoxGroup>
          <Grid />
          <Grid
            item
            sm={12}
            className={(this.classes.item, this.classes.forwardbutton)}
          >
            <IconButton
              edge="start"
              // className={classes.forwardbutton}
              color="black"
              onClick={this.props.handleDetails2}
            >
              <ArrowForward />
            </IconButton>
            {/* <HorizontalNonLinearStepWithError />*/}
          </Grid>
        </Grid>
      </Grid>
    );
  }
}

export default withStyles(styles)(FormEmergencyType);

Это может быть связано с файлом настроек, но я не знаю, в чем может быть причина.Здесь вы можете увидеть файл index.js, который вызывает файл FormEmergencyType.js:

import React from 'react';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
import { Container } from '@material-ui/core';
import { Header } from '../Layout';
import FormPersonType from './FormPersonType';
import FormEmergencyType from './FormEmergencyType';
import AppContext from '../utils/AppContext';
import CONST from '../utils/Constants';

class SOS extends React.Component {
  static contextType = AppContext;

  constructor(props) {
    super(props);
    this.state = {
      timerOn: false,
      componentType: 'type_of_person',
      ambulance: false,
      fire_service: false,
      police: false,
      car_service: false,
      meAffected: false,
      anotherPerson: false
    };

    this.handleComponentType = this.handleComponentType.bind(this);
    this.handleEmergencyType = this.handleEmergencyType.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  showSettings(event) {
    event.preventDefault();
  }

  handleComponentType(e) {
    console.log(e);
    this.setState({ componentType: 'type_of_emergency' });
  }

  handleEmergencyType(new_emergency_state) {
    console.log(new_emergency_state);
    this.setState(new_emergency_state);
  }

  handleDetails2() {
    this.props.history.push('/emergency_details2');
  }

  onSubmit(e) {
    console.log('in OnSubmit');
    axios
      .post(CONST.URL + 'emergency/create', {
        id: 1,
        data: this.state
      })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    let component;

    if (this.state.componentType === 'type_of_person') {
      component = (
        <FormPersonType
          handleComponentType={this.handleComponentType}
          personTypes={this.state}
        />
      );
    } else if (this.state.componentType === 'type_of_emergency') {
      component = (
        <FormEmergencyType
          handleComponentType={this.handleComponentType}
          handleEmergencyType={this.handleEmergencyType}
          handleDetails2={this.handleDetails2}
          emergencyTypes={this.state}
          timerStart={this.timerStart}
          onSubmit={this.onSubmit}
        />
      );
    }

    return (
      <React.Fragment>
        <Header title="Send out SOS" />
        <Container component="main" maxWidth="sm">
          {component}
        </Container>
        {/*component = (
        <HorizontalNonLinearStepWithError
          handleComponentType={this.handleComponentType}
        />*/}
      </React.Fragment>
    );
  }
}

экспорт по умолчанию с помощью роутера (SOS);

Буду очень признателен за вашу помощь!

1 Ответ

0 голосов
/ 26 июня 2019

Это потому, что вы не связали свою функцию handleDetails2, в консоли вы видите эту ошибку при нажатии на последнюю стрелку:

react-dom.production.min.js:232 Uncaught TypeError: Cannot read property 'props' of undefined
    at value (index.js:47)

Просто привяжите ее, как вы сделали для других функций в вашемconstructor

this.handleDetails2 = this.handleDetails2.bind(this)

или сделайте функцию стрелки

handleDetails2 = () => this.props.history.push('/emergency_details2');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...