【问题标题】:How to avoid the 'no-param-reassign' rule with a input's handleChange?如何使用输入的 handleChange 避免“无参数重新分配”规则?
【发布时间】:2019-07-29 18:44:45
【问题描述】:

我正在努力构建一个 React Textarea,它会随着用户键入而自动增长/缩小。我构建了受此 codepen 启发的组件:https://codepen.io/Libor_G/pen/eyzwOx

虽然我的这个工作很好,但我遇到了一个 es-lint 错误,我不确定如何正确解决。 eslint 不喜欢我在 handleChange 函数中使用事件参数。

解决此问题的正确方法是什么?

我的 REACT UIC:

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const TEXTAREA_LINE_HEIGHT = 24;
const PADDING = 16;

const StyledTextArea = styled.textarea`
  resize: none;
  width: 100%;
  padding: ${PADDING}px;

  line-height: ${TEXTAREA_LINE_HEIGHT}px;
  font-size: 17px;
`;


class TextArea extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      rows: 1,
      minRows: 1,
      maxRows: 3,
    };
  }

  handleChange = (event) => {
    const { minRows, maxRows } = this.state;


    const previousRows = event.target.rows;
    event.target.rows = minRows; // reset number of rows in textarea

    const currentRows = Math.floor((event.target.scrollHeight - (PADDING * 2)) / TEXTAREA_LINE_HEIGHT);

    if (currentRows === previousRows) {
      event.target.rows = currentRows;
    }

    if (currentRows >= maxRows) {
      event.target.rows = maxRows;
      event.target.scrollTop = event.target.scrollHeight;
    }

    this.setState({
      value: event.target.value,
      rows: currentRows < maxRows ? currentRows : maxRows,
    });
  };

  render = () => {
    const {
      name,
      placeholder,
    } = this.props;

    return (
      <StyledTextArea
        innerRef={(ref) => {
          this.textAreaRef = ref;
        }}
        name={name}
        placeholder={placeholder}
        rows={this.state.rows}
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }
}

TextArea.defaultProps = {
  name: null,
  placeholder: null,
};

TextArea.propTypes = {
  name: PropTypes.string,
  placeholder: PropTypes.string,
};

export default TextArea;

【问题讨论】:

  • 这是因为你正在修改event.target的dom属性值
  • 您既可以不将参数分配给新值,也可以禁用函数参数的规则,例如 /*eslint no-param-reassign: ["error", { "props": false }]*/ 您可以将其添加到顶部的文件中,也可以将其添加到 .eslintrc 文件中一个全球性的影响。这是该规则的文档eslint.org/docs/rules/no-param-reassign
  • 我讨厌使用 es-lint 忽略,有没有办法在不忽略 eslint 的情况下实现相同的规则?谢谢
  • @AnApprentice 在这种情况下,您可以尝试将事件分配给另一个变量,例如 const ev = event 并改用 ev
  • @IbraheemAl-Saady 哇,好用。谢谢。请留下答案,以便我接受。

标签: javascript reactjs eslint styled-components


【解决方案1】:

您可以禁用我在评论中提到的规则,如下所示: /*eslint no-param-reassign: ["error", { "props": false }]*/

或者如果你不想忽略 eslint,你可以将你的参数分配给一个新变量:

const ev = event 并且您可以使用 ev 代替 event。

【讨论】:

    猜你喜欢
    • 2018-05-20
    • 2019-10-07
    • 2011-01-22
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多