[已解決] 解決方法是:1)'擴展React.Component'不再自動綁定。 2)'filterText'變量需要發送'handleUserInput(filterText)'...React組件錯誤(輸入)
謝謝大家!
美好的一天。 此代碼正在處理「React.createClass」,現在我試圖將其更改爲「擴展React.Component」。 目的是通過輸入值來對元素進行排序。
的代碼:
TheSecondComponent...
constructor(props){
super(props);
}
handleChange() {
this.props.onUserInput(
this.refs.filterTextInput.value
);
}
render() {
return (
<form className='Center'>
<input
type="text"
value={this.props.filterText}
ref="filterTextInput"
onChange={this.handleChange}
/>
</form>
);
}
TheFirstComponent...
constructor(){
super();
this.state={'filterText': ''} // If to use setState here than I have one
more error, added in the end of the question
this.handleUserInput=this.handleUserInput.bind(this);
}
getInitialState() {
return {
filterText: ''
};
}
handleUserInput(filterText) {
//this.setState({filterText: filterText});
this.state = {filterText: filterText};
}
render() {
return (
<div>
<div>
<SearchBar
filterText={this.state.filterText}
onUserInput={this.handleUserInput}
/>
<CreateButtons
source={this.props.citys}
filterText={this.state.filterText}
/>
</div>
</div>
);
}
的WORKING代碼 「React.createClass」 的:
TheFirstComponent...
({
handleChange: function() {
this.props.onUserInput(
this.refs.filterTextInput.value
);
},
render: function() {
return (
<form className='Center'>
<input
type="text"
value={this.props.filterText}
ref="filterTextInput"
onChange={this.handleChange}
/>
</form>
);
}
});
TheSecondComponent...
({
getInitialState: function() {
return {
filterText: ''
};
},
handleUserInput: function(filterText) {
this.setState({
filterText: filterText
});
},
render: function() {cl(this);
return (
<div>
<div className='SLFirst'>
<SearchBar
filterText={this.state.filterText}
onUserInput={this.handleUserInput}
/>
<CreateButtons
source={this.props.citys}
filterText={this.state.filterText}
/>
</div>
</div>
);
}
});
有一個錯誤: 我想輸入的任何文本「輸入」但它不寫入值。我的意思是,我在打字,但沒有任何變化。是因爲
this.state={'filterText': ''}
?
我應該怎麼玩?如果不設置''而是'一些文本',那麼這個'sometext'將是不可修改的。
由於我發現「setState」不再有效。 如果使用 '的setState',那麼有oooone更多:
TypeError: Cannot read property 'filterText' of null
40 | <div>
41 | <div className='SLFirst'>
42 | <SearchBar
> 43 | filterText={this.state.filterText}
44 | onUserInput={this.handleUserInput}
45 | />
46 | <CreateButtons
'的onChange = {this.handleChange.bind(這)}'ES6類需要結合上下文 –
謝謝你的答覆。有一個新的錯誤。只需秒,將在問題 –
'onUserInput = {this.handleUserInput.bind(this)}'中通過它,或者更好地在任何地方使用箭頭函數。 –