2017-06-03 60 views
0

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

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

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

然后,我打电话给我的部件,像这样:

<InputComponent maxLength={10} /> 
+3

'

Remaining: {this.props.maxLength - this.state.whateverYouNamedTheValue.length}
'? –

+0

谢谢!这工作完美:) – sfmaysf

回答

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> 
     ); 
    } 
} 
+0

谢谢!这完美地回答了这个问题。 – sfmaysf