
[英]Reactjs: The value of the input element, required for a controlled component
[英]ReactJS OnKeyUp event not getting value on controlled input
我正在构建一个ReactJS搜索组件,用于通过搜索进行数据过滤。
这个想法是用户在一个接一个字母后输入一个单词,系统将过滤包含该单词的所有寄存器。 基本组件详述如下:
class SearchInput extends Component {
static propTypes = {
onKeyUp: PropTypes.func,
placeHolder: PropTypes.string,
value: PropTypes.string
};
state = {
searchText: ""
};
handleKeyUp = event => {
console.log(event.target.value) // <== No result. Always empty
let newSearchText = event.target.value;
this.setState({ searchText: newSearchText });
if (this.props.onKeyUp) this.props.onKeyUp(newSearchText);
};
render() {
console.log(this.state.searchText) // <== Always empty
return (
<div className="search-input">
<div className="search-input-icon">
<Icon name="faSearch" />
</div>
<input
autoFocus="true"
type="text"
onKeyUp={this.handleKeyUp}
placeholder={this.props.placeHolder}
value={this.state.searchText}
/>
</div>
);
}
我没有得到handleKeyUp
事件处理程序的按键值。
如果我从代码中省略value={this.state.searchText}
(不受控制),它可以工作,但是我需要一种方法来从组件外部设置searchText
(初始化,其他组件选择等)。
为什么我没有在我的处理程序上获取event.target.value
数据? 怎么解决?
用这个:
let newSearchText = event.target.getAttribute('value')
尝试使用event.key
。
event.target.value
只指向尚未设置的this.state.searchText
。
好像你忘了在构造函数上绑定函数:
class SearchInput extends Component {
constructor(props) {
super(props);
this.handleKeyUp = this.handleKeyUp.bind(this);
}
//... any code here
handleKeyUp = event => {
console.log(event.target.value);
}
render() {
//... any code here
<input
autoFocus="true"
type="text"
onKeyUp={this.handleKeyUp}
placeholder={this.props.placeHolder}
value={this.state.searchText}
/>
}
}
我很确定你必须在输入字段上监听onChange
事件才能获得更新的目标值。 简单地改变
<input onKeyUp={this.handleKeyUp} />
至
<input onChange={this.handleKeyUp} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.