React 的函數組件和類組件中的props


React 的函數組件和類組件中的props

函數組件

函數組件中的props是一個對象直接作為函數的參數傳入,在組件內容中可以直接用點語法使用props對象中的屬性,代碼如下:

function Test1(props) {
        return(
            <div>
                The user is <b>{props.isLoggedIn? 'jack':'not'} </b>logged in.
            </div>
        )
    }
    const element = <Test isLoggedIn={true}/>;
    ReactDOM.render(
        element,
        document.getElementById('app')
    )

類組件

在劉組件中的props存放在this中,這一點和VUE中的props類似,但是Vue可以直接使用this后跟屬性名,但是React中還需要this.props后跟相對應的屬性名.

class Test extends React.Component{
        render(){
            return(
                <div>
                    The user is <b>{this.props.isLoggedIn? 'jack':'not'} </b>logged in.
                </div>
            )
        }
    }
    const element = <Test isLoggedIn={true}/>;
    ReactDOM.render(
        element,
        document.getElementById('app')
    )

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM