如何通过输入的handleChange避免“无参数重新分配”规则?

时间:2019-03-07 19:16:21

标签: javascript reactjs eslint styled-components

我正在努力构建一个随用户输入自动增长/缩小的React Textarea。我受此代码笔启发而构建了我的组件: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;

1 个答案:

答案 0 :(得分:1)

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

或者,如果您不想忽略eslint,则可以将参数分配给新变量:

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