react 不能像vue一样,不能使用双向绑定,只能使用单向绑定
单向 表单 绑定事件
onChange
<input type="tetx" val={this.state.val} onChange={this.hanInput}/>
hanInput=(event)=>{ //获取input 输入的值
console.log(event.target.value); //通过es5的语法来获取内容
this.setState({
val:event.target.value
})
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
class Hello extends React.Component{
//第一个是组件初始化(initialization)阶段
constructor(props){
//初始化状态
super(props)
//初始化状态
this.state={
name:'jack',
age:31,
npg:'我喜欢---哈哈',
list:['1','2'],
val:'',//input的初始化的值
}
this.updateUsertwos=this.updateUsertwos.bind(this);
}
//第二个是组件的挂载(Mounting)阶段
componentWillMount(){
console.log('组件加载前----------componentWillMount')
}
componentDidMount(){
console.log('组件加载后--------componentDidMount')
}
hanInput=(event)=>{ //获取input 输入的值
console.log(event.target.value); //通过es5的语法来获取内容
this.setState({
val:event.target.value
})
}
//button 点击事件
hdClick=()=>{
const {val,list}=this.state; //获取到val 和 list
//es5 写法
// val=this.state.val;
// list=this.state.list
list.push(val); //把输入的内容 push到list里面
this.setState({ //赋值
list:list
})
console.log('listpush----',list)
}
render(){
//当时数据发生更新的是混 render 函数会更新一次
const arr=this.state.list;
let listitem=arr.map((item,index)=>{
return <li key={index}>{item}</li>
})
console.log('组件的加载和数据的更新------render')
return <div>
<ul>{listitem}</ul>
<div>表单</div>
<input type="tetx" val={this.state.val} onChange={this.hanInput}/>
<button onClick={this.hdClick}>点击新增数据</button>
<div>---------------------------</div>
</div>
}
ReactDOM.render(
<Hello></Hello>,
document.getElementById('example')
)
</script>
</body>
</html>
image.png
网友评论