我需要一个带有去抖搜索的输入字段,并且值应该从父组件传递。但当从父组件传递值时,它不起作用。正确的实施方法是什么?
代码沙盒示例https://codesandbox.io/embed/debounce-input-owdwj 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}
/>
);
}
}
存储文本字段值的父组件
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>
);
}
}
这里的问题是您仅在 300 秒后更新组件,这也不会更新输入框。首先,每当有按键时,您需要更新搜索框组件,并且稍后可以在 300 秒后通知家长更改
我已经更新了您的代码参考,请查看https://codesandbox.io/embed/debounce-input-gm50t https://codesandbox.io/embed/debounce-input-gm50t
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)