【问题标题】:Show character limit under input in React Js在 React Js 中的输入下显示字符限制
【发布时间】:2017-06-03 22:21:48
【问题描述】:

我正在创建一个反应输入组件,并且需要在输入前显示字符限制:(剩余 0/500 个字符)。我已将 maxLength 作为道具传递给输入组件,但不确定如何显示达到限制之前剩余的字符数。

最大长度正常工作 - 如何添加显示剩余字符数的视觉反馈(2/500 个字符......等)。

<input
    {...customAttributes}
    maxLength={maxLength}
    required={required}
/> 

然后我这样调用我的组件:

<InputComponent maxLength={10} />

【问题讨论】:

  • &lt;div&gt;Remaining: {this.props.maxLength - this.state.whateverYouNamedTheValue.length}&lt;/div&gt; ?
  • 谢谢!这工作得很好:)

标签: javascript html reactjs


【解决方案1】:

该问题没有足够的信息来正确回答,但根据对评论的反应,这样的事情应该有效:

<div>
    {this.props.maxLength - this.state.whateverYouNamedTheValue.length}/{this.props.maxLength}
</div>

在组件的上下文中,用 ES6 清理了一下:

class InputComponent extends React.Component {
    // ... class and state stuff ...
    render() {
        const { maxLength } = this.props;
        const { whateverYouNamedTheValue } = this.state;

        return (
            <div>
                <input
                    {...customAttributes}
                    maxLength={maxLength}
                    required={required}
                />
                { whateverYouNamedTheValue ? (
                    <div>
                        ({ maxLength - whateverYouNamedTheValue.length }/{ maxLength })
                    </div>
                ) : null }
            </div>
        );
    }
}

【讨论】:

  • 谢谢!这完美地回答了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 2016-02-16
  • 1970-01-01
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多