使用組件字段的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}
/>
);
React本身建議在構造函數中重新綁定事件處理程序,即'this.handleChange = this.handleChange.bind(this)'或者使用ES6箭頭函數,即'handleChange =(event)=> {...}'試過嗎?閱讀:https://facebook.github.io/react/docs/handling-events.html –
嘗試重新綁定的方式和ES6箭頭,不起作用。我也嘗試了一個簡單的函數onChange = {(e)=> console.log(e)}。不工作呢!老實說,這超出了我的理解...... – hhelbawi
你記得從'render'函數中刪除綁定嗎? –