国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

第二章React全家桶之面向組件編程

這篇具有很好參考價(jià)值的文章主要介紹了第二章React全家桶之面向組件編程。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

一、組件的基本理解和使用

組件是 React的一等公民,使用React就是在用組件 組件表示頁(yè)面中的部分功能 組合多個(gè)組件實(shí)現(xiàn)完整的頁(yè)面
功能特點(diǎn):可復(fù)用、獨(dú)立、可組合

1-1、函數(shù)式組件

適用于簡(jiǎn)單組件(無(wú)狀態(tài)的組件)

<script type="text/babel">
        // 定義函數(shù)式組件
        function Demo(){
            return <h2>我是函數(shù)定義的組件</h2>
        }
        // 渲染組件到頁(yè)面
        ReactDOM.render(<Demo/>,document.getElementById('test'))
        // 執(zhí)行了ReactDOM.render(<Demo/>之后發(fā)生了什么
            // 1.React解析組件標(biāo)簽,找到了Demo組件
            // 2.發(fā)現(xiàn)組件式使用函數(shù)定義的,隨后調(diào)用該函數(shù),將返回的虛擬dom轉(zhuǎn)為真實(shí)dom,隨后呈現(xiàn)在頁(yè)面中

    </script>

1-2、類(lèi)式組件

適用于復(fù)雜組件(有狀態(tài)的組件)

<script type="text/babel">
        // 創(chuàng)建類(lèi)式組件
        class Demo extends React.Component {
            render(){
                // 這里的this指向類(lèi)的實(shí)例對(duì)象
                console.log(this);
                // render式放在哪里的?Demo的原型對(duì)象上,供實(shí)例使用
                return  <h2>我是類(lèi)式組件適用于復(fù)雜組件的定義</h2>
            }
        }

        // 渲染組件到頁(yè)面
        ReactDOM.render(<Demo />,document.getElementById('test'))
        // 執(zhí)行了ReactDOM.render(<Demo/>之后發(fā)生了什么
            // 1.React解析組件標(biāo)簽,找到了Demo組件
            // 2.發(fā)現(xiàn)組件式使用函數(shù)定義的,隨后new出來(lái)該類(lèi)的實(shí)例,通過(guò)該實(shí)例,調(diào)用到原型上的render方法
            // 3.將render返回的虛擬dom轉(zhuǎn)為真實(shí)dom,渲染到頁(yè)面上
    </script>

二、組件實(shí)例的三大核心屬性

2-1、state的基本使用

<script type="text/babel">
        // 定義函數(shù)式組件
        class Weather extends React.Component{
           //構(gòu)造器調(diào)用幾次? ———— 1次
			constructor(props){
				console.log('constructor');
				super(props)
				//初始化狀態(tài)
				this.state = {isHot:false}
				//解決changeWeather中this指向問(wèn)題
				this.changeWeather = this.changeWeather.bind(this)
			}

            render(){
                console.log('render');
				//讀取狀態(tài)
				const {isHot} = this.state
				return <h1 onClick={this.changeWeather}>今天天氣很{isHot ? '炎熱' : '涼爽'}</h1>
            }
            //changeWeather調(diào)用幾次? ———— 點(diǎn)幾次調(diào)幾次
			changeWeather(){
				//changeWeather放在哪里? ———— Weather的原型對(duì)象上,供實(shí)例使用
				//由于changeWeather是作為onClick的回調(diào),所以不是通過(guò)實(shí)例調(diào)用的,是直接調(diào)用
				//類(lèi)中的方法默認(rèn)開(kāi)啟了局部的嚴(yán)格模式,所以changeWeather中的this為undefined
				console.log('changeWeather');
				//獲取原來(lái)的isHot值
				const isHot = this.state.isHot
				//嚴(yán)重注意:狀態(tài)必須通過(guò)setState進(jìn)行更新,且更新是一種合并,不是替換。
				this.setState({isHot:!isHot})
				console.log(this);
				//嚴(yán)重注意:狀態(tài)(state)不可直接更改,下面這行就是直接更改?。。?/span>
				//this.state.isHot = !isHot //這是錯(cuò)誤的寫(xiě)法
			}
        }
        // 渲染組件到頁(yè)面
        ReactDOM.render(<Weather/>,document.getElementById('test'))
        // 執(zhí)行了ReactDOM.render(<Demo/>之后發(fā)生了什么
            // 1.React解析組件標(biāo)簽,找到了Demo組件
            // 2.發(fā)現(xiàn)組件式使用函數(shù)定義的,隨后調(diào)用該函數(shù),將返回的虛擬dom轉(zhuǎn)為真實(shí)dom,隨后呈現(xiàn)在頁(yè)面中

    </script>
2-2-1、state的總結(jié)

1.state是組件對(duì)象中最重要的屬性,值是對(duì)象【可以包含多個(gè)key-value的組合】
2.組件唄稱(chēng)為狀態(tài)機(jī),通過(guò)更新組件的state來(lái)更新對(duì)應(yīng)頁(yè)面現(xiàn)實(shí)【重新渲染組件】

強(qiáng)烈注意:

  1. 組件中render方法中的this為組件實(shí)例。
  2. 組件的自定義方法中的this為undefine,如何解決?
    a:強(qiáng)制綁定this,通過(guò)函數(shù)對(duì)象的bind()
    b:箭頭函數(shù)
  3. 狀態(tài)數(shù)據(jù),不能直接修改或更新。

2-2、props的基本使用

2-2-1、props的傳值與批量傳值
<script type="text/babel">
        // 定義函數(shù)式組件
        class Person extends React.Component{
            render(){
                console.log(this);
                return (
                    <ul>
                    <li>姓名:{this.props.name}</li>
                    <li>性別:{this.props.sex}</li>
                    <li>年齡:{this.props.age}</li>    
                </ul>
                )
            }
        }
        // 渲染組件到頁(yè)面
        ReactDOM.render(<Person name="Zhangsan" age="12" sex="男"/>,document.getElementById('test1'))
        ReactDOM.render(<Person name="lisi" age="12" sex="男"/>,document.getElementById('test2'))
        ReactDOM.render(<Person name="wangwu" age="12" sex="男"/>,document.getElementById('test3'))
        // 批量傳值
        let info = {name:'四六',age:'23',sex:'女'}
        ReactDOM.render(<Person {...info}/>,document.getElementById('test4'))
    </script>
2-2-2、對(duì)props進(jìn)行限制
<script type="text/babel">
        // 定義函數(shù)式組件
        class Person extends React.Component{
            render(){
                return (
                    <ul>
                    <li>姓名:{this.props.name}</li>
                    <li>性別:{this.props.sex}</li>
                    <li>年齡:{this.props.age}</li>    
                </ul>
                )
            }
        }
        // 對(duì)props的值進(jìn)行限制
        Person.propTypes = {
            name:PropTypes.string.isRequired,//限制name必傳并且是字符串型
            sex:PropTypes.string,//限制sex是字符串型
            age:PropTypes.number,//限制age是數(shù)值型
            speak:PropTypes.func//限制speak是函數(shù)型
        }
        // 給props默認(rèn)值
        Person.defaultProps = {
            name:'未知'
        }
        // 渲染組件到頁(yè)面
        ReactDOM.render(<Person name="Zhangsan" age={21} sex="男" speak={()=>{}}/>,document.getElementById('test1'))
        // 批量傳值
        let info = {name:'李四',age:23,sex:'女'}
        ReactDOM.render(<Person {...info}/>,document.getElementById('test2'))
    </script>
2-2-3、props的簡(jiǎn)寫(xiě)
<script type="text/babel">
        // 定義函數(shù)式組件
        class Person extends React.Component {
            // 對(duì)props的值進(jìn)行限制
            static propTypes = {
                name: PropTypes.string.isRequired,//限制name必傳并且是字符串型
                sex: PropTypes.string,//限制sex是字符串型
                age: PropTypes.number,//限制age是數(shù)值型
                speak: PropTypes.func//限制speak是函數(shù)型
            }
            // 給props默認(rèn)值
            static defaultProps = {
                name: '未知'
            }

            render() {
                return (
                    <ul>
                        <li>姓名:{this.props.name}</li>
                        <li>性別:{this.props.sex}</li>
                        <li>年齡:{this.props.age}</li>
                    </ul>
                )
            }
        }


        // 渲染組件到頁(yè)面
        ReactDOM.render(<Person name="Zhangsan" age={21} sex="男" speak={() => { }} />, document.getElementById('test1'))
        // 批量傳值
        let info = { name: '李四', age: 23, sex: '女' }
        ReactDOM.render(<Person {...info} />, document.getElementById('test2'))
    </script>
2-2-4、類(lèi)式組件中的構(gòu)造器與props
 //構(gòu)造器調(diào)用幾次? ———— 1次
			constructor(props){
				console.log('constructor',props);
				super(props)
				//初始化狀態(tài)
				this.state = {isHot:false}
				//解決changeWeather中this指向問(wèn)題
				this.changeWeather = this.changeWeather.bind(this)
			}

注意事項(xiàng):

1.構(gòu)造器是否接收props,是否傳遞給super,是否希望在構(gòu)造器中通過(guò)this訪問(wèn)props,就取決于是否使用構(gòu)造器接收peops,開(kāi)發(fā)中不寫(xiě)構(gòu)造器,能省略就省略

2-2-5、函數(shù)式組件中使用props
<script type="text/babel">
        // 定義函數(shù)式組件
        function Person(props){
            return (
                <ul>
                    <li>姓名:{props.name}</li>
                    <li>性別:{props.sex}</li>
                    <li>年齡:{props.age}</li>    
                </ul>
            )
        }
        // 對(duì)props的值進(jìn)行限制
        Person.propTypes = {
            name:PropTypes.string.isRequired,//限制name必傳并且是字符串型
            sex:PropTypes.string,//限制sex是字符串型
            age:PropTypes.number,//限制age是數(shù)值型
            speak:PropTypes.func//限制speak是函數(shù)型
        }
        // 給props默認(rèn)值
        Person.defaultProps = {
            name:'未知'
        }

        // 渲染組件到頁(yè)面
        // 批量傳值
        let info = {name:null,age:23,sex:'女'}
        ReactDOM.render(<Person {...info}/>,document.getElementById('test2'))
    </script>

注意事項(xiàng):

1.函數(shù)式組件只能使用props,不能使用state和refs

2-3、refs的基本使用

2-3-1、字符串形式的ref
 <script type="text/babel">
        // 創(chuàng)建組件
        class Ref extends React.Component{
            showData = ()=>{
                const {input1} = this.refs
                alert(input1.value)
            }
            showData2 = ()=>{
                const {input2} = this.refs
                alert(input2.value)
            }
            render(){
                return (
                    <div>
                        <input ref="input1" type="text" placeholder="點(diǎn)擊按鈕展示數(shù)據(jù)" />  
                        <button onClick={this.showData}>點(diǎn)擊展示左側(cè)數(shù)據(jù)</button>  
                        <input onBlur={this.showData2} ref="input2"  type="text" placeholder="失去焦點(diǎn)展示數(shù)據(jù)"/>    
                    </div>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<Ref />,document.getElementById('test'))
    </script>
2-3-2、回調(diào)函數(shù)形式的ref
 <script type="text/babel">
        // 創(chuàng)建組件
        class Ref extends React.Component{
            showData = ()=>{
                const {input1} = this
                alert(input1.value)
            }
            showData2 = ()=>{
                const {input2} = this
                alert(input2.value)
            }
            render(){
                return (
                    <div>
                        <input ref={a=>this.input1 = a} type="text" placeholder="點(diǎn)擊按鈕展示數(shù)據(jù)" />  
                        <button onClick={this.showData}>點(diǎn)擊展示左側(cè)數(shù)據(jù)</button>   
                        <input onBlur={this.showData2} ref={a=>this.input2 = a} type="text" placeholder="失去焦點(diǎn)展示數(shù)據(jù)" /> 
                    </div>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<Ref />,document.getElementById('test'))
    </script>
2-3-3、回調(diào)函數(shù)形式的ref的調(diào)用次數(shù)問(wèn)題

注意:

1.內(nèi)聯(lián)函數(shù)的形式會(huì)造成回調(diào)函數(shù)調(diào)用兩次第一次為null,第二次為綁定的屬性

<script type="text/babel">
        // 創(chuàng)建組件
        class Ref extends React.Component{
            showData = ()=>{
                const {input1} = this
                alert(input1.value)
            }
            changeWeather = ()=>{
                const {isHot} = this.state
                this.setState({isHot:!isHot})
            }
            saveInput = (a)=>{
                this.input1 = a; 
                console.log('@',a);
            }
            state = {isHot:false}
            render(){
                const {isHot} = this.state
                return (
                    <div>
                        <h2>今天的天氣很{isHot ? '炎熱' : '寒冷'}</h2>
                        {/*以下內(nèi)聯(lián)形式的回調(diào)會(huì)造成回調(diào)執(zhí)行兩次,第一次為null,第二次為綁定的屬性標(biāo)簽,先調(diào)集展示測(cè)試功能,在點(diǎn)擊切換天氣控制臺(tái)查看執(zhí)行次數(shù)*/}
                        { /*<input ref={(a)=>{this.input1 = a; console.log('@',a);}} type="text" placeholder="點(diǎn)擊按鈕展示數(shù)據(jù)" />*/  }
                        <input ref={this.saveInput} type="text" placeholder="點(diǎn)擊按鈕展示數(shù)據(jù)" />
                        <button onClick={this.showData}>點(diǎn)擊展示左側(cè)數(shù)據(jù)</button>   
                        <button onClick={this.changeWeather}>點(diǎn)我切換天氣</button>
                    </div>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<Ref />,document.getElementById('test'))
    </script>
2-3-4、creatRef

注意:

1.creatRef創(chuàng)建的自己myRef是專(zhuān)人專(zhuān)用的,只能有一個(gè)節(jié)點(diǎn)使用這個(gè)myRef,如果有多個(gè)會(huì)被最后一個(gè)覆蓋

<script type="text/babel">
        // 創(chuàng)建組件
        class Ref extends React.Component{
            myRef1 = React.createRef()
            myRef2 = React.createRef()
            showData = ()=>{
                alert(this.myRef1.current.value)
            }
            showData2 = ()=>{
                alert(this.myRef2.current.value)
            }
          
            render(){
                return (
                    <div>
                        <input ref={this.myRef1} type="text" placeholder="點(diǎn)擊按鈕展示數(shù)據(jù)" />  
                        <button onClick={this.showData}>點(diǎn)擊展示左側(cè)數(shù)據(jù)</button>   
                        <input onBlur={this.showData2}  ref={this.myRef2}  type="text" placeholder="失去焦點(diǎn)展示數(shù)據(jù)" /> 
                    </div>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<Ref />,document.getElementById('test'))
    </script>

三、React的事件處理

注意:

1.通過(guò)onXxx屬性指定事件處理函數(shù)
2.React使用的是自定義(合成事件),而不是使用的原生DOM事件
3.React中的事件是通過(guò)事件委托方式處理的(委托給徐建最外層的元素)
4.通過(guò)event.target得到發(fā)生事件的DOM元素對(duì)象

script type="text/babel">
        // 創(chuàng)建組件
        class Ref extends React.Component{
            myRef1 = React.createRef()
            myRef2 = React.createRef()
            showData = ()=>{
                alert(this.myRef1.current.value)
            }
            showData2 = (e)=>{
                alert(e.target.value)
            }
          
            render(){
                return (
                    <div>
                        <input ref={this.myRef1} type="text" placeholder="點(diǎn)擊按鈕展示數(shù)據(jù)" />  
                        <button onClick={this.showData}>點(diǎn)擊展示左側(cè)數(shù)據(jù)</button>   
                        <input onBlur={this.showData2}   type="text" placeholder="失去焦點(diǎn)展示數(shù)據(jù)" /> 
                    </div>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<Ref />,document.getElementById('test'))
    </script>

四、收集表單數(shù)據(jù)

4-1、非受控組件

<script type="text/babel">
        class Login extends React.Component{
            subFn = (e)=>{
                e.preventDefault()
                const {username,password} = this
                alert(username.value)
            }
            render(){
                return (
                    <form  onSubmit={this.subFn}>
                        用戶(hù)名:<input  ref={c=>this.username = c} type="text" />    
                        密碼:<input ref={c=>this.password = c}  type="password" />  
                       <button>登錄</button>
                    </form>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<Login />,document.getElementById('test'))
    </script>

4-2、受控組件

<script type="text/babel">
        class Login extends React.Component{
            state = {
                username:"",
                password:''
            }
            subFn = (e)=>{
                e.preventDefault()
                const {username,password} = this.state
                alert(`您輸入的用戶(hù)名是${username},您輸入的密碼是${password}`)
            }
            saveUsername = (e)=>{
                this.setState({username:e.target.value})
            }
            savePassword = (e)=>{
                this.setState({password:e.target.value})
            }
            render(){
                return (
                    <form  onSubmit={this.subFn}>
                        用戶(hù)名:<input onChange={this.saveUsername}  type="text" />    
                        密碼:<input onChange={this.savePassword}   type="password" />  
                       <button>登錄</button>
                    </form>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<Login />,document.getElementById('test'))
    </script>

五、生命周期(舊)

原理圖
第二章React全家桶之面向組件編程,React,react.js,javascript,前端

生命周期的三個(gè)階段(舊)
1. 初始化階段: 由ReactDOM.render()觸發(fā)---初次渲染
	1.constructor()
	2.componentWillMount()
	3.render()
	4.componentDidMount()
2. 更新階段: 由組件內(nèi)部this.setSate()或父組件重新render觸發(fā)
	1.shouldComponentUpdate()
	2.componentWillUpdate()
	3.render()
	4.componentDidUpdate()
3. 卸載組件: 由ReactDOM.unmountComponentAtNode()觸發(fā)
	1.componentWillUnmount()

代碼演示

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>React生命周期</title>
</head>

<body>
    <div id="test"></div>
    <!-- 引入react核心庫(kù) -->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!-- 引入react-dom 用于支持react操作dom -->
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <!-- 引入bable,用于將jsx轉(zhuǎn)為js -->
    <script type="text/javascript" src="../js/babel.min.js"></script>

    <script type="text/babel">
        class Count extends React.Component {
            constructor(props) {
                super(props)
                // 初始化狀態(tài)
                this.state = { count: 0 }
                console.log('constructor');
            }

            // 組件即將要掛載
            componentWillMount() {
                console.log('componentWillMount');
            }
            // 組件掛載完成的鉤子
            componentDidMount() {
                console.log('componentDidMount');
            }
            // 組件將要卸載的鉤子
            componentWillUnmount() {
                console.log('componentWillUnmount');
            }
            // 控制組件更新的閥門(mén)
            shouldComponentUpdate() {
                console.log('shouldComponentUpdate');
                return true
            }
            // 組件將要更新的鉤子
            componentWillUpdate() {
                console.log('componentWillUpdate');
            }
            // 組件更新完畢的鉤子
            componentDidUpdate() {
                console.log('componentDidUpdate');
            }
            render() {
                console.log('render');
                const { count } = this.state
                return (
                    <div>
                        <h2>當(dāng)前求和為:{count}</h2>
                        <button onClick={this.add}>點(diǎn)我加一</button>
                        <button onClick={this.death}>卸載組件</button>
                        <button onClick={this.force}>不更新任何狀態(tài),舊強(qiáng)制 更新一下</button>
                    </div>
                )
            }

            // 加一的處理函數(shù)
            add = () => {
                const { count } = this.state
                this.setState({ count: count + 1 })
            }
            // 卸載組件的回調(diào)
            death = () => {
                ReactDOM.unmountComponentAtNode(document.getElementById('test'))
            }
            // 強(qiáng)制更新按鈕的回調(diào)
            force = () => {
                this.forceUpdate()
            }
        }

        class A extends React.Component {
            // 初始化狀態(tài)
            state = {carName:'奔馳'}
            changeCar = ()=>{
                this.setState({carName:'寶馬'})
            }
            render() {
                return (
                    <div>
                        <div>我是A組件</div>
                        <button onClick={this.changeCar}>換車(chē)</button>
                        <B carName={this.state.carName}/>
                    </div>
                )
            }
        }
        class B extends React.Component {
            
            // 組件將要接收到新的props值
            componentWillReceiveProps(){
                console.log('B--componentWillReceiveProps');
            }
             // 控制組件更新的閥門(mén)
             shouldComponentUpdate() {
                console.log('B--shouldComponentUpdate');
                return true
            }
            // 組件將要更新的鉤子
            componentWillUpdate() {
                console.log('B--componentWillUpdate');
            }
            // 組件更新完畢的鉤子
            componentDidUpdate() {
                console.log('B--componentDidUpdate');
            }
            render() {
                return (
                    <div>我是B組件,接收的車(chē)是:{this.props.carName}</div>
                )
            }
        }
        // 展示數(shù)據(jù)
        ReactDOM.render(<A />, document.getElementById('test'))
    </script>
</body>

</html>

六、生命周期(新)

原理圖
與舊的生命周期來(lái)比廢除了舊生命周期的三個(gè)鉤子,新提出了兩個(gè)新的生命周期鉤子第二章React全家桶之面向組件編程,React,react.js,javascript,前端文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-532542.html

生命周期的三個(gè)階段(新)
1. 初始化階段: 由ReactDOM.render()觸發(fā)---初次渲染
	1.constructor()
	2.getDerivedStateFromProps 
	3.render()
	4.componentDidMount()
2. 更新階段: 由組件內(nèi)部this.setSate()或父組件重新render觸發(fā)
	1.getDerivedStateFromProps
	2.shouldComponentUpdate()
	3.render()
	4.getSnapshotBeforeUpdate
	5.componentDidUpdate()
3. 卸載組件: 由ReactDOM.unmountComponentAtNode()觸發(fā)
	1.componentWillUnmount()
重要的勾子
	1.render:初始化渲染或更新渲染調(diào)用
	2.componentDidMount:開(kāi)啟監(jiān)聽(tīng), 發(fā)送ajax請(qǐng)求
	3.componentWillUnmount:做一些收尾工作, : 清理定時(shí)器
即將廢棄的勾子
	1.componentWillMount
	2.componentWillReceiveProps
	3.componentWillUpdate
現(xiàn)在使用會(huì)出現(xiàn)警告,下一個(gè)大版本需要加上UNSAFE_前綴才能使用,以后可能會(huì)被徹底廢棄,不建議使用。

6-1.getDerivedStateFromProps

<script type="text/babel">
        class Count extends React.Component {
            // 構(gòu)造器
            constructor(props) {
                super(props)
                // 初始化狀態(tài)
                this.state = { count: 0 }
                console.log('constructor');
            }

            // 若state的值在任何時(shí)候都取決于props,那么可以使用getDerivedStateFromProps
            static getDerivedStateFromProps(props,state){
                console.log('getDerivedStateFromProps');
                // return出去的狀態(tài)舊不會(huì)被修改了
                return props
            }

            // 組件掛載完成的鉤子
            componentDidMount() {
                console.log('componentDidMount');
            }
            // 組件將要卸載的鉤子
            componentWillUnmount() {
                console.log('componentWillUnmount');
            }
            // 控制組件更新的閥門(mén)
            shouldComponentUpdate() {
                console.log('shouldComponentUpdate');
                return true
            }
            
            // 組件更新完畢的鉤子
            componentDidUpdate() {
                console.log('componentDidUpdate');
            }
            render() {
                console.log('render');
                const { count } = this.state
                return (
                    <div>
                        <h2>當(dāng)前求和為:{count}</h2>
                        <button onClick={this.add}>點(diǎn)我加一</button>
                        <button onClick={this.death}>卸載組件</button>
                        <button onClick={this.force}>不更新任何狀態(tài),舊強(qiáng)制 更新一下</button>
                    </div>
                )
            }

            // 加一的處理函數(shù)
            add = () => {
                const { count } = this.state
                this.setState({ count: count + 1 })
            }
            // 卸載組件的回調(diào)
            death = () => {
                ReactDOM.unmountComponentAtNode(document.getElementById('test'))
            }
            // 強(qiáng)制更新按鈕的回調(diào)
            force = () => {
                this.forceUpdate()
            }
        }

        // 展示數(shù)據(jù)
        ReactDOM.render(<Count />, document.getElementById('test'))
    </script>

6-2.getSnapshotBeforeUpdate的使用場(chǎng)景

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>getSnapShotBeforeUpdate的使用場(chǎng)景</title>
	<style>
		.list{
			width: 200px;
			height: 150px;
			background-color: skyblue;
			overflow: auto;
		}
		.news{
			height: 30px;
		}
	</style>
</head>
<body>
	<!-- 準(zhǔn)備好一個(gè)“容器” -->
	<div id="test"></div>
	
	<!-- 引入react核心庫(kù) -->
	<script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
	<!-- 引入react-dom,用于支持react操作DOM -->
	<script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
	<!-- 引入babel,用于將jsx轉(zhuǎn)為js -->
	<script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

	<script type="text/babel">
		class NewsList extends React.Component{

			state = {newsArr:[]}

			componentDidMount(){
				setInterval(() => {
					//獲取原狀態(tài)
					const {newsArr} = this.state
					//模擬一條新聞
					const news = '新聞'+ (newsArr.length+1)
					//更新?tīng)顟B(tài)
					this.setState({newsArr:[news,...newsArr]})
				}, 1000);
			}

			getSnapshotBeforeUpdate(){
				return this.refs.list.scrollHeight
			}

			componentDidUpdate(preProps,preState,height){
				this.refs.list.scrollTop += this.refs.list.scrollHeight - height
			}

			render(){
				return(
					<div className="list" ref="list">
						{
							this.state.newsArr.map((n,index)=>{
								return <div key={index} className="news">{n}</div>
							})
						}
					</div>
				)
			}
		}
		ReactDOM.render(<NewsList/>,document.getElementById('test'))
	</script>
</body>
</html>

到了這里,關(guān)于第二章React全家桶之面向組件編程的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶(hù)投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 第二章 React項(xiàng)目配置ESlint和Prettier實(shí)現(xiàn)自動(dòng)格式化代碼以及統(tǒng)一代碼風(fēng)格

    第二章 React項(xiàng)目配置ESlint和Prettier實(shí)現(xiàn)自動(dòng)格式化代碼以及統(tǒng)一代碼風(fēng)格

    歡迎加入本專(zhuān)欄!本專(zhuān)欄將引領(lǐng)您快速上手React,讓我們一起放棄放棄的念頭,開(kāi)始學(xué)習(xí)之旅吧!我們將從搭建React項(xiàng)目開(kāi)始,逐步深入講解最核心的hooks,以及React路由、請(qǐng)求、組件封裝以及UI(Ant Design)框架的使用。讓我們一起掌握React,開(kāi)啟前端開(kāi)發(fā)的全新篇章! 需要準(zhǔn)

    2024年02月03日
    瀏覽(92)
  • 《Jetpack Compose從入門(mén)到實(shí)戰(zhàn)》 第二章 了解常用UI組件

    《Jetpack Compose從入門(mén)到實(shí)戰(zhàn)》 第二章 了解常用UI組件

    書(shū)附代碼 Google的圖標(biāo)庫(kù) ConstraintLayout約束布局需要依賴(lài):implementation “androidx.constraintlayout:constraintlayout-compose: $constraintlayout _version” 《Jetpack Compose從入門(mén)到實(shí)戰(zhàn)》第一章 全新的 Android UI 框架 《Jetpack Compose從入門(mén)到實(shí)戰(zhàn)》 第二章 了解常用UI組件 《Jetpack Compose從入門(mén)到實(shí)戰(zhàn)》

    2024年02月07日
    瀏覽(26)
  • 曲線(xiàn)藝術(shù)編程 coding curves 第二章 三角函數(shù)曲線(xiàn)(TRIG CURVES)

    曲線(xiàn)藝術(shù)編程 coding curves 第二章 三角函數(shù)曲線(xiàn)(TRIG CURVES)

    原作:Keith Peters 原文:https://www.bit-101.com/blog/2022/11/coding-curves/ 譯者:池中物王二狗(sheldon) blog: http://cnblogs.com/willian/ 源碼:github: https://github.com/willian12345/coding-curves 曲線(xiàn)藝術(shù)編程系列 第二章 這是與曲線(xiàn)相關(guān)最基礎(chǔ)簡(jiǎn)單的一章,但我會(huì)用幾個(gè)不同的示例來(lái)演示。我不會(huì)深入詳

    2024年02月07日
    瀏覽(24)
  • Linux高性能服務(wù)器編程 學(xué)習(xí)筆記 第二章 IP協(xié)議詳解

    Linux高性能服務(wù)器編程 學(xué)習(xí)筆記 第二章 IP協(xié)議詳解

    本章從兩方面探討IP協(xié)議: 1.IP頭部信息。IP頭部出現(xiàn)在每個(gè)IP數(shù)據(jù)報(bào)中,用于指定IP通信的源端IP地址、目的端IP地址,指導(dǎo)IP分片和重組,指定部分通信行為。 2.IP數(shù)據(jù)報(bào)的路由和轉(zhuǎn)發(fā)。IP數(shù)據(jù)報(bào)的路由和轉(zhuǎn)發(fā)發(fā)生在除目標(biāo)機(jī)器外的所有主機(jī)和路由器上,它們決定數(shù)據(jù)報(bào)是否應(yīng)

    2024年02月09日
    瀏覽(31)
  • UNIX網(wǎng)絡(luò)編程卷一 學(xué)習(xí)筆記 第二十二章 高級(jí)UDP套接字編程

    UNIX網(wǎng)絡(luò)編程卷一 學(xué)習(xí)筆記 第二十二章 高級(jí)UDP套接字編程

    TCP是一個(gè)字節(jié)流協(xié)議,又使用滑動(dòng)窗口,因此沒(méi)有記錄邊界或發(fā)送者數(shù)據(jù)發(fā)送能力超過(guò)接收者接收能力之類(lèi)的事情,但對(duì)于UDP,每個(gè)輸入操作對(duì)應(yīng)一個(gè)UDP數(shù)據(jù)報(bào)(一個(gè)記錄),因此當(dāng)收取的數(shù)據(jù)報(bào)大于引用的輸入緩沖區(qū)時(shí)就有問(wèn)題。 UDP是不可靠協(xié)議,但有些應(yīng)用確實(shí)有理由使

    2024年02月12日
    瀏覽(29)
  • 第二章(第二節(jié)):無(wú)窮小量和函數(shù)

    若 lim f(x) = 0 , 則稱(chēng)函數(shù) f(x) 當(dāng) x → x 0 時(shí)是無(wú)窮小量,簡(jiǎn)稱(chēng): 無(wú)窮小 。 ???? x→ x 0 定理1. 有限多個(gè) 無(wú)窮小量的代數(shù)和仍是無(wú)窮小量 定理2. 有限多個(gè) 無(wú)窮小量的積也是無(wú)窮小量 定理3.常數(shù)與無(wú)窮小量的積也是無(wú)窮小量 定理4.有界變量與無(wú)窮小量的積是無(wú)窮小量 當(dāng) x→

    2024年02月08日
    瀏覽(38)
  • [React]面向組件編程

    [React]面向組件編程

    - 函數(shù)式定義(簡(jiǎn)單組件),使用 function 定義 - 類(lèi)式定義(復(fù)雜組件),使用 class 定義 - 原始定義,需要在constructor中定義state和綁定方法handleClick的this - 簡(jiǎn)化后在類(lèi)中直接給state和handleClick賦值,就直接把屬性和方法綁定到Weather的實(shí)例上了 - 函數(shù)式組件使用props - 類(lèi)式組件使

    2024年02月11日
    瀏覽(94)
  • React面向組件編程

    React面向組件編程

    使用React開(kāi)發(fā)者工具調(diào)試 效果 函數(shù)式組件: 類(lèi)式組件: 復(fù)雜組件的狀態(tài)state如何理解: 組件中的狀態(tài)驅(qū)動(dòng)頁(yè)面渲染 組件實(shí)例對(duì)象生成的state 注意 1.組件名必須首字母大寫(xiě) 2.虛擬DOM元素只能有一個(gè)根元素 3.虛擬DOM元素必須有結(jié)束標(biāo)簽 渲染類(lèi)組件標(biāo)簽的基本流程 1.React內(nèi)部會(huì)創(chuàng)

    2023年04月27日
    瀏覽(72)
  • React 面向組件編程(下)

    React 面向組件編程(下)

    在React面向組件編程中,除了上一章節(jié)的組件實(shí)例的三大核心屬性以外,還有很多重要的內(nèi)容比如:React 的生命周期,受控組件與非受控組件,高階函數(shù)和函數(shù)柯里化的理解等,在本文中會(huì)給大家繼續(xù)講解React 面向組件編程中剩余的內(nèi)容。 受控組件 非受控組件 多數(shù)情況下,

    2024年02月02日
    瀏覽(30)
  • React面向組件編程(上)

    React組件中默認(rèn)封裝了很多屬性,有的是提供給開(kāi)發(fā)者操作的,其中有三個(gè)屬性非常重要:state、props、refs。通過(guò)這三大核心屬性的使用,我們能夠?qū)崿F(xiàn)對(duì)組件的狀態(tài)進(jìn)行更新。 state 是一個(gè)對(duì)象,它包含組件的數(shù)據(jù)狀態(tài),當(dāng)狀態(tài)變化時(shí),會(huì)觸發(fā)視圖的更新。你可以理解它的作

    2023年04月09日
    瀏覽(16)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包