总代码:
import React, {Component, Fragment} from 'react'
class App extends Component {
constructor(props){
super(props)
this.state = {
inputValue: ''
}
this.handleInputChange = this.handleInputChange.bind(this)
}
render(){
return(
<Fragment>
<input
value={this.state.inputValue}
onChange={this.handleInputChange}
/>
</Fragment>
)
}
handleInputChange(e){
const value = e.target.value
this.setState(() => ({
inputValue: value
}))
}
}
export default App
1、数据要保存在this.state
中
constructor(props){
super(props)
this.state = {
inputValue: ''
}
}
2、在JSX
中使用js的代码
,要用{}
包裹
<input
value={this.state.inputValue}
/>
3、在JSX中使用函数钩子
on后的第一个字母要大写
- 要
通过bind改变this指向
,否则在函数中的this会变成undefined
this.handleInputChange = this.handleInputChange.bind(this)
<input
onChange={this.handleInputChange}
/>
4、改变this.state中的值,要用this.setState()函数
handleInputChange(e){
const value = e.target.value
this.setState(() => ({
inputValue: value
}))
}
5、当组件的 state 或 props 发生改变,组件的 render 会重新执行一次