2017-03-20 23 views
0

使用組件字段的redux-form,我試圖顯示輸入中寫入的字符串的長度。但是,似乎handleChange函數永遠不會被onChange觸發。 這裏是組件:字段組件中的道具「onChange」不會觸發給定的函數

import React from 'react'; 
import {Field} from 'redux-form'; 

var max_chars = 160; 
var LimitedCharsField = React.createClass({ 
    getInitialState: function() { 
     return { 
      chars_left: max_chars 
     }; 
    }, 
    handleChange(event) { 
     var input = event.target.value; 
     this.setState({ 
      chars_left: max_chars - input.length 
     }); 
    }, 
    render: function() { 
     return (
      <div> 
       <Field name="short_description" id="short_description" component={this.props.renderSmallTextField} type="text" 
         label="Qualification du site" onChange={this.handleChange.bind(this)} maxLength={max_chars}/> 
       <br/> 

       <small id="short_description_countdown" >{this.state.chars_left} caractères restants</small> 

      </div> 
     ); 
    } 
}); 


export default LimitedCharsField; 

,我在其中是主要形式的父組件調用:

<LimitedCharsField renderSmallTextField={renderSmallTextField}/> 

組件會出現在形式,但handleChange這麼想的火在所有。

爲了得到函數handleChange應該做些什麼?

非常感謝。

編輯:下面的renderSmallTextField

const renderSmallTextField = ({input, label, meta:{touched, error}, ...custom}) => (
    <TextField 
     hintText={label} 
     errorText={touched && error} 
     {...input} 
     {...custom} 
    /> 
); 
+0

React本身建議在構造函數中重新綁定事件處理程序,即'this.handleChange = this.handleChange.bind(this)'或者使用ES6箭頭函數,即'handleChange =(event)=> {...}'試過嗎?閱讀:https://facebook.github.io/react/docs/handling-events.html –

+0

嘗試重新綁定的方式和ES6箭頭,不起作用。我也嘗試了一個簡單的函數onChange = {(e)=> console.log(e)}。不工作呢!老實說,這超出了我的理解...... – hhelbawi

+0

你記得從'render'函數中刪除綁定嗎? –

回答

0

我猜想這是因爲道具的onChange周圍不正確地傳遞。雖然沒有看到renderSmallTextField組件的代碼,但肯定不能說。嘗試設置component="input"作爲一個簡單的測試。如果handleChange方法開始啓動,你已經發現你的問題。

+0

感謝您的回答,我用renderSmallTextField更新了我的問題。我將組件值更改爲「輸入」,但該功能也未觸發。 – hhelbawi