(事件名大写)json
注意:组件事件须要配合状态,因此如今没法呈现效果bash
class Cmp1 extends React.Component{
constructor(...args){
super(..args);
this.a=0;//要用状态,属性不行,props也不行
}
add(){
this.a++;
//这个函数会执行,a也会变,可是不会从新渲染
alert(this.a);
}
render(){
return <div>
//强制绑定add的this
<input type="button" value="加1" onClick={this.add.bind(this)} />
</div>
}
}
复制代码
a其实变了,可是只有状态改变能引起从新渲染
组件的状态很是有用函数
class Cmp1 entends React.Component{
constructor(...args){
super(...args);
//状态初始化
this.state={a:0}
}
add(){
//修改状态
this.setState({
a:this.state.a+1
})
}
render(){
return <div>
//强制绑定add的this
<input type="button" value="+1" onClick={this.add.bind(this)} />
{this.state.a}
</div>
}
}
let comp=<Cmp1></Cmp1>
ReactDOM.render(comp,root)复制代码
注意⚠️:性能
class Parent extends React.Component{
constructor(...args){
super(...args);
this.state={a:0}
}
render(){
return <div>
<input type="button" value="+1" onClick={function(){
this.setState({
a:this.state.a+1
})
}.bind(this)} />
<Child a={this.state.a} />
</div>
}
}
class Child extends React.Component{
constructor(...args){
super(...args);
}
render(){
return <div>
{this.props.a}
</div>
}
}
复制代码
class Cmp1 extends React.Component{
constructor(.;..args){
super(...args);
this.a=12;
}
fn(){
this.a++
//强制渲染
this.forceUpdate();
}
render(){
return <div>
<input type="button" value="+1" onClick={this.fn.bind(this)} />
{this.a}
</div>
}
}
复制代码
强制从新渲染会打乱React自身的渲染计划,轻则影响性能,重则引起错误,极少使用
从组件建立到销毁的整个过程fetch
上图中,涉及最重要的两个钩子函数, componentDidMount(组件已挂载)和 componentDidUpdate(组件已更新)
建立阶段(mount)ui
更新阶段(update)this
阻止更新spa
shouldComponentUpdata(nextProps,nextState){
//当前状态(变化前),新状态(变化后)
this.state.nextState
//当前属性,新属性
this.props.nextProps
return true -容许更新/。 false -拒绝更新
}复制代码
使用实例:阻止循环updatecode
class Parent entends React.Component{
constructor(...args){
super(..args);
this.state={
id:1
}
}
next(){
this.setState{
id:this.state.id+1
}
}
render(){
return {
<div>
<input type="button" value="下一个" onClick={this.next.bind(this)}/>
<Child id={this.state.id}/>
</div>
}
}
}
class Child extends React.Component{
constructor(..args){
super(...args);
this.state={
name:'',
age:''
}
}
shouledComponentUpdata(nextProps,nextState){
//console.log(nextProps,this.props);
renturn{
//条件1:属性变了(来自父级)
nextProps.id!=this.props.id||
//条件2:状态变了(来自本身)
nextState.name!=this.state.name
};
}
loadData(id){
fetch(`data/data${id}.txt`).then(res=>{
res.json().then(data=>{
this.setState(data);
});
});
}
componentDidMount(){
console.log('初始:‘,this.props.id); this.loadData(this.props.id) } componentDidUpdate(){ console.log('更新‘,this.props.id)
this.loadData(this.props.id);
}
render(){
console.log('渲染‘); return ( <div> ID:{this.props.id}<br/> 用户名:{this.state.name},年龄:{this.state.age} </div> ) } }复制代码
销毁操做没法阻止