reactjs - 我可以从 componentDidMount 调用 onChange 事件吗
问题描述
在我的 React 应用程序中,我有以下代码:
...
handleChange(event) {
let chunkedText = []
this.setState({value: event.target.value});
let text = event.target.value
...
//store the text in local storage with the key 'tweet'
window.localStorage.setItem('tweet', text);
...
componentDidMount() {
//once the component loads check local storage and update the value if it exists
if(window.localStorage.getItem('tweet')) {
this.setState({value: window.localStorage.getItem('tweet')});
}
}
render() {
return (
<div>
<form>
<label>
<textarea
placeholder="Begin typing your tweet here..."
rows="14" cols="50" value={this.state.value}
onChange={this.handleChange}
/>
</label>
</form>
{this.state.length > 0 ? <span>{this.state.length} Chars || {this.state.count} Tweets</span> : ''}
</div>
);
}
}
请注意,在 componentDidMount 中,我们从本地存储中提取一些文本并设置状态。理想情况下,在此之后(在 componentDidMount 中)我想运行 handleChange。这样做的正确方法是什么?
解决方案
我会将代码更改为以下内容:
handleChange(event) {
this.handleValue(event.target.value);
}
handleValue(value) {
let chunkedText = []
this.setState({ value: value });
let text = value
//...
//store the text in local storage with the key 'tweet'
window.localStorage.setItem('tweet', text);
//...
}
componentDidMount() {
//once the component loads check local storage and update the value if it exists
if (window.localStorage.getItem('tweet')) {
this.handleValue(window.localStorage.getItem('tweet'))
}
}
render() {
return (
<div>
<form>
<label>
<textarea
placeholder="Begin typing your tweet here..."
rows="14" cols="50" value={this.state.value}
onChange={this.handleChange}
/>
</label>
</form>
{this.state.length > 0 ? <span>{this.state.length} Chars || {this.state.count} Tweets</span> : ''}
</div>
);
}
推荐阅读
- typescript - 用函数参数中更具体的类型替换“未知”时出错
- jquery-ui-autocomplete - 如何使用 chrome 的检查器检查自动完成小部件?
- angular - 有人在离子角度中使用过 JSON1 扩展吗?
- java - 将整数值添加到 Java 中的集合
- excel - 如何在 IF 函数上设置最大回报百分比?
- asp.net-core - 清理 ServiceCollection 和 ServiceProvider 的“Pre”实例的正确方法?
- c++ - arduino mqttclient 回调,这是一个类方法函数
- c# - 无效的回发或回调参数。启用事件验证... - 仅在 IIS 10 Selenium 测试下
- angular - 没有名称空间“数学”Angular 6的模块
- r - 是否可以选择 left_join 列表列?