无法在react应用程序中使用set状态设置userName


import React, { Component } from 'react';
import './App.css';
class App extends Component {
state = {
userName: 'yfky',
length: 10
};
onClickHandler = (event) => {
console.log(event.target.value);
this.setState({userName : event.target.value})
};
calculate = () => {
// const len = this.userName.length
console.log(this.userName);
this.setState({length: this.userName.length})
}
render() {
return (
<div className="App">
<input
onChange={(event) => this.onClickHandler(event)} />
<button onClick={this.calculate}></button>
{this.length}
</div>
);
}
}
export default App;
calculate = () => {
// const len = this.userName.length
console.log(this.userName);
this.setState({length: this.userName.length})
}

您正在将userName和长度保存在state对象中。

所以你必须执行this.state来访问状态对象

calculate = () => {
// const len = this.userName.length
console.log(this.state.userName);
this.setState({length: this.state.userName.length})
}

最新更新