2017-06-03 176 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