4 javascript debouncing reactjs
我需要一个带有去抖搜索的输入字段,并且值应该从父组件传递。但是当从父组件传递值时它不起作用。正确的实施方法是什么?
Codesandbox 示例https://codesandbox.io/embed/debounce-input-owdwj
具有去抖功能的文本字段
class MyTextField extends Component {
search = _.debounce(event => {
this.props.onChange(event.target.value);
}, 300);
handleChangeInput = event => {
event.persist();
this.search(event);
};
render() {
return (
<TextField
value={this.props.value}
placeholder="type"
onChange={this.handleChangeInput}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
存储文本字段值的父组件
class Form extends Component {
state = {
value: ""
};
handleChangeInput = value => {
this.setState({
value
});
};
render() {
return (
<div>
<h2>{this.state.value}</h2>
<MyTextField
value={this.state.value}
onChange={this.handleChangeInput}
/>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这里的问题是您仅在 300 秒后更新组件,这也不会更新输入框。首先,只要有按键,您就需要更新搜索框组件,稍后家长可以在 300 秒后收到更改通知。我已经更新了您的代码参考,请查看https://codesandbox.io/embed/debounce-input -gm50t
| 归档时间: |
|
| 查看次数: |
1401 次 |
| 最近记录: |