React事件绑定属性的命名采用小驼峰式写法。
绑定函数的过程中不加() 否则函数会立即执行
1 React中阻止默认行为使用preventDefault();
事件处理—传递参数
向事件处理函数中传递参数。
方式1(推荐):通过 bind 的方式进行传递
方式2:通过箭头函数传递。注意使用箭头函数调用事件对象必须显式的进行传递
事件处理—修改this指向(面试常问)
方式1:通过bind方法进行原地绑定,从而改变this指向
方式2:通过创建箭头函数
方式3:在constructor中提前对事件进行绑定
方式4:将事件调用的写法改为箭头函数的形式
React状态提升
React中的状态提升概括来说,就是多个组件需要反映相同的变化数据,提升到它们最近的父组件上.在父组件上改变这个状态然后通过props分发给子组件.
两个子组件需要利用到对方的状态的话,那么这个时候我们就需要使用到状态提升
案例
<script type="text/babel">
class MyCom extends React.Component{
constructor(props){
super(props)
this.state={
arr:[
{name:"德玛西亚"},
{name:"维恩"},
{name:"压索"},
{name:"劫"}
]
}
}
fun=()=>{
console.log(this.demoinp.value)
if(this.demoinp.value==""){
return
}
var newarr=[...this.state.arr,{name:this.demoinp.value}]
this.setState({
arr: newarr
})
this.demoinp.value=""
}
del(i){
if(confirm("确定删除?")){
this.state.arr.splice(i,1)
this.setState({
arr:this.state.arr
})
}
}
render() {
return(
<div>
<input ref={(input)=>{this.demoinp=input}} type="text"/>
<button onClick={this.fun}>添加</button>
<ul>
{
this.state.arr.map((val,i)=>{
return (
<div>
<li key={i}>{val.name}<button onClick={this.del.bind(this,i)}>删除</button></li>
</div>
)
})
}
</ul>
</div>
)
}
}
ReactDOM.render(<MyCom/>,document.getElementById("app"))
</script>