【发布时间】:2017-12-18 10:08:12
【问题描述】:
[已解决] 解决方案是:1)“扩展 React.Component”不再自动绑定。 2) 需要发送 'filterText' 变量 'handleUserInput(filterText)'...
谢谢大家!!
美好的一天。 此代码正在处理“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>
);
}
“React.createClass”的WORKING代码:
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' 那么这个 'sometext' 将是不可更改的。
我发现“setState”不再起作用。 如果要使用'setState',那就再多点:
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(this)}es6类需要绑定上下文 -
感谢您的回复。有新的错误。几秒钟,将在问题中过去它
-
onUserInput={this.handleUserInput.bind(this)}或在任何地方更好地使用箭头函数。 -
@NanduKalidindi 对不起,是的,我做到了。我有这种绑定功能的情况。请查看已编辑的问题
标签: javascript reactjs