1:model改变视图view
把model
里面的值赋给input
,即把this.state
里面的username
值给了input
,当页面加载的时候,model
层就能改变视图view
。
model
this.state = {
username:'111'
}
view
代码语言:javascript复制<input value={this.state.username} ></input>
2:同理反过来,view改变反过来影响model
监听 onChange事件
代码语言:javascript复制 onChange={this.inputChange}
封装方法
代码语言:javascript复制inputChange = (e) => {
this.setState({
username: e.target.value
})
}
代码语言:javascript复制import React, { Component } from 'react';
import photo from '../asset/images/photo.jpg';
import '../asset/css/index.css'
class Home extends Component {
constructor() {
super();
//react定义数据
this.state = {
username:'134567811'
}
}
inputChange = (e) => {
this.setState({
username: e.target.value
})
}
setUsername=(e)=>{
this.setState({
username: '肖战'
})
}
render() {
return (
<div>
<h2>双向数据绑定</h2>
{/* 2:同理反过来,view改变反过来影响model */}
{this.state.username}
<input value={this.state.username} onChange={this.inputChange}></input>
{/* 1:model改变视图view */}
<button onClick={this.setUsername}>改变username的值</button>
</div>
)
}
}
export default Home;