Шутка: Функциональные компоненты не могут быть предоставлены ссылки. Попытки получить доступ к этой ссылке потерпят неудачу - PullRequest
0 голосов
/ 08 февраля 2020

Я использую библиотеку react-final-form и jest.

Почему я все еще получаю это предупреждение? Ref работает нормально, я могу очистить значение select всякий раз, когда я переключаю вкладки. Я пытался переместить компонент select из вкладок, но это предупреждение все еще отображается.

result

Мой компонент выглядит так:

import React, { Component, createRef } from 'react';
import Select from 'react-select';
import { Field } from 'react-final-form';
import { TextField } from 'final-form-material-ui';
import { withStyles } from '@material-ui/core';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import Paper from '@material-ui/core/Paper';

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`wrapped-tabpanel-${index}`}
      aria-labelledby={`wrapped-tab-${index}`}
      {...other}
    >
      {value === index && <Box p={1}>{children}</Box>}
    </Typography>
  );
}

class SelectPrimaryContactUser extends Component {
  constructor(props) {
    super(props);
    this.primaryContactSelectRef = createRef();

    this.state = {
      activeTab: 0,
      selectedUser: props.value ? props.users.find(user => user.value === props.value) : null,
    };
  }

  handleChangeUser = option => {
    this.setState({
      selectedUser: option,
    });
  };

  handleTabSwitch = (event, newValue) => {
    const { handleCreateNewUserFieldsFlag } = this.props;

    if (newValue === 1 && this.primaryContactSelectRef.current) {
      this.primaryContactSelectRef.current.select.clearValue();
    }
    if (handleCreateNewUserFieldsFlag) {
      handleCreateNewUserFieldsFlag(newValue === 1);
    }

    this.setState({
      activeTab: newValue,
    });
  };

  render() {
    const { users, showCreateNewUser, classes, firstNameLabel, lastNameLabel, emailLabel, phoneLabel, selectUserPlaceholder } = this.props;
    const { selectedUser, activeTab } = this.state;

    return (
      <Box mt={2} className={classes.box}>
        {showCreateNewUser && (
          <Paper square className={classes.paper}>
            <Tabs
              value={activeTab}
              onChange={this.handleTabSwitch}
              indicatorColor="primary"
              variant="fullWidth"
              textColor="primary"
            >
              <Tab label="Select existing user" className={classes.tab} data-testid="select-existing-user-button" />
              {showCreateNewUser && (
                <Tab label="Invite new user" className={classes.tab} data-testid="invite-new-user-button" />
              )}
            </Tabs>
          </Paper>
        )}
        <TabPanel value={activeTab} index={0}>
          <Field
            name="primary_contact_id"
            render={({ input, meta }) => (
              <div style={{ marginTop: 15 }}>
                <Select
                  ref={this.primaryContactSelectRef}
                  placeholder={selectUserPlaceholder}
                  value={selectedUser}
                  isClearable
                  options={users}
                  onChange={option => {
                    input.onChange(option !== null ? option.value : null);

                    this.handleChangeUser(option);
                  }}
                  onBlur={event => input.onBlur(event)}
                  styles={{
                    control: provided => ({
                      ...provided,
                      borderColor: (meta.error || meta.submitError) && meta.touched ? '#f44336' : provided.borderColor,
                    }),
                  }}
                />
              </div>
            )}
          />
        </TabPanel>
        <TabPanel value={activeTab} index={1}>
          <div>
            <Box mb={2}>
              <Field
                fullWidth
                name="primary_contact_first_name"
                component={TextField}
                type="text"
                label={firstNameLabel}
              />
            </Box>

            <Box mb={2}>
              <Field
                fullWidth
                name="primary_contact_last_name"
                component={TextField}
                type="text"
                label={lastNameLabel}
              />
            </Box>

            <Box mb={2}>
              <Field fullWidth name="primary_contact_email" component={TextField} type="text" label={emailLabel} />
            </Box>

            <Field fullWidth name="primary_contact_phone" component={TextField} type="text" label={phoneLabel} />
          </div>
        </TabPanel>
      </Box>
    );
  }
}

const styles = theme => ({
});

export default withStyles(styles)(SelectPrimaryContactUser);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...