Перейдите по клику на кнопку Material-UI - работает только один раз - PullRequest
1 голос
/ 11 ноября 2019

Я пытаюсь заключить кнопку Material-UI в другой компонент. Все идет хорошо, если я не пытался обработать событие onClick. Кажется, что он работает только один раз.

(не) Рабочий пример доступен по адресу:

https://codesandbox.io/embed/material-demo-nn0ut?fontsize=14

Исходный код:

import React from "react";
import { useState } from "react";
import MaterialButton from "@material-ui/core/Button";
import { Component } from "react";
import { withStyles } from "@material-ui/core";

const stylesMain = {
  root: {
    fontSize: 16
  }
};

const stylesSecondary = {
  root: {
    fontSize: 14
  }
};

const StyledButtonMain = withStyles(stylesMain)(MaterialButton);
const StyledButtonSecondary = withStyles(stylesSecondary)(MaterialButton);

class Button extends Component {
  constructor(props) {
    super(props);
    this.onClick = function() {};
    this.href = null;
    this.target = null;
    this.type = "button";
    if (props.onClick) {
      this.onClick = props.onClick;
    }
    if (props.href) {
      this.href = props.href;
    }
    if (props.target) {
      this.target = props.target;
    }
    if (props.type) {
      this.type = props.type;
    }
  }

  render() {
    const StyledButton =
      this.props.color === "secondary"
        ? StyledButtonSecondary
        : StyledButtonMain;
    return (
      <StyledButton
        type={this.type}
        href={this.href}
        target={this.target}
        onClick={this.onClick}
        variant="contained"
        style={{ whiteSpace: "nowrap" }}
      >
        {this.props.children}
      </StyledButton>
    );
  }
}

export default function Counter(props) {
  const [counter, setCounter] = useState(0);
  return (
    <div>
      <h1>Counter: {counter}</h1>
      <Button
        onClick={() => {
          setCounter(counter + 1);
        }}
      >
        ClickMe
      </Button>
    </div>
  );
}

IВы ожидали, что OnClick должен работать так же, как и в «голой» кнопке пользовательского интерфейса. Как я могу это исправить?

1 Ответ

0 голосов
/ 11 ноября 2019

Вы теряете значение onClick () между рендерами. При первоначальной загрузке он будет устанавливать его на основе реквизита, но затем в следующий раз при рендеринге теряет значение, так как вы не загружаете его снова.

Вы можете просто использовать реквизит, как показано ниже, и использовать троичныйоператоры, как я сделал для onClick для нулевых проверок, если вы хотите

class Button extends Component {

  render() {
    const StyledButton =
      this.props.color === "secondary"
        ? StyledButtonSecondary
        : StyledButtonMain;
    return (
      <StyledButton
        type={this.props.type}
        href={this.props.href}
        target={this.props.target}
        onClick={this.props.onClick ? this.props.onClick : () => {}}
        variant="contained"
        style={{ whiteSpace: "nowrap" }}
      >
        {this.props.children}
      </StyledButton>
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...