B站 React教程笔记day1(3)其他API
5. 其他API
5.1 无状态组件
当我们现在的组件仅仅是为了呈递一些DOM元素,没有state、props等东西,此时可以不用费劲
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。class My extends React.Component{}
而是一个暴露简单函数即可:
My.js
import React from "react"; export default () => { return ( <div> <h1>我是My组件</h1> </div> ) }
此时可以直接使用:
import React from "react"; import My from "./My.js"; class App extends React.Component{ constructor(){ super(); } render(){ return ( <div> <My></My> </div> ) } } //向外暴露 export default App;
5.2 默认属性
如果没有传入name输入,那么就以“菜鸟”作为属性:
constructor(props){ super(); this.state = { name : props.name || "菜鸟" } }
5.3 组件的生命周期
组件提供了可以触发事件的函数接口,就是生命周期。
组件的生命周期包含三个部分:
挂载(Mounting):组件被插入到DOM中
更新(Updating):组件被重新渲染,查明DOM是否应该刷新
移除(Unmounting):组件从DOM中移除
React为每一个状态都提供了两种处理函数,will
函数在进入状态之前调用,did
函数在进入状态之后调用,三种状态共计五种处理函数。
componentWillMount()
componentDidMount()
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
componentWillUnmount()
此外,React 还提供两种特殊状态的处理函数。
componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用
//挂载之前 componentWillMount(){ console.log("componentWillMount"); } //在挂载结束之后马上被调用。需要DOM节点的初始化操作应该放在这里。ajax在这里,等到请求成功,再用 this.setState 方法重新渲染 UI componentDidMount(){ console.log("componentDidMount"); } //当组件做出是否要更新DOM的决定的时候被调用。“门神”,在改变状态的时候可以选择通过或者不通过。 shouldComponentUpdate(nextProps , nextState){ if(nextState.a > 0.8){ return true; } alert("本次没有随机到大于0.8的,更新被阻止"); return false; } //在更新发生之前被调用,没有把门的功能 componentWillUpdate(){ console.log("componentWillUpdate"); } //在组件移除和销毁之前被调用 componentWillUnmount(){ console.log("componentWillUnmount"); }
5.4 React 中的表单
模拟双向绑定:
import React from "react"; class My2 extends React.Component{ constructor(props){ super(); // 将 this.change 绑定到 组件中 this.change = (this.change).bind(this); this.state = { "txt" : "" } } change(event){ this.setState({"txt" : event.target.value }); } render(){ return ( <div> <input type="text" onInput={this.change} /> <h1>{this.state.txt}</h1> </div> ) } } export default My2;
5.5 ref DOM 钩子
import React from 'react' class My3 extends React.Componnet { constructor(props) { super() } render() { return ( <div> <input type="button" val="点我" onClick="()=>{this.refs.mybox.style.color = "red"}} /"> <div className="box" ref="mybox" style={{"color": "green"}}></div> </div> ) } }

更多精彩