[英]How to avoid the 'no-param-reassign' rule with a input's handleChange?
我正在努力构建一个随着用户输入自动增长/缩小的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;
您可以像我在评论中提到的那样禁用该规则,如下所示: /*eslint no-param-reassign: ["error", { "props": false }]*/
或者,如果您不想忽略eslint,则可以将参数分配给新变量:
const ev = event
,您可以使用ev代替event。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.