1. 程式人生 > >React--配置元件的props

React--配置元件的props

元件內部是通過 this.props 的方式獲取到元件的引數的,如果 this.props 裡面有需要的屬性我們就採用相應的屬性,沒有的話就用預設的屬性。

總結:

  1. 為了使得元件的可定製性更強,在使用元件的時候,可以在標籤上加屬性來傳入配置引數。

  2. 元件可以在內部通過 this.props 獲取到配置引數,元件可以根據 props 的不同來確定自己的顯示形態,達到可配置的效果。

  3. 可以通過給元件新增類屬性 defaultProps 來配置預設引數。

  4. props 一旦傳入,你就不可以在元件內部對它進行修改。但是你可以通過父元件主動重新渲染的方式來傳入新的 props,從而達到更新的效果。

練習

開啟和關閉電腦

完成兩個元件,電腦 Computer 和顯示器 Screen。 電腦有個 status 狀態表示電腦現在是開還是關的,status 為 on 為開,status 為 off 為關,預設狀態為 off。電腦有個按鈕,點選可以自由切換電腦的開關狀態。 顯示器接受一個名為 showContent 的 props,顯示器會把它內容顯示出來。如果不傳入 showContent,顯示器顯示 “無內容”。 電腦包含顯示器,當電腦狀態為開的時候顯示器顯示“顯示器亮了”,否則顯示“顯示器關了”。

//電腦 Computer 
class Computer extends Component
{ constructor(){ super() this.state={status:'off'} } open(){ this.setState({ {status:this.state.status =='off'?'on':'off'} }) } render(){ return( <div> <button onClick={this.open.bind(this)}>開關<
/button> <Screen showContent={this.state.status=='off'?'顯示器關了':'顯示器開了'}/> </div> ) } }] //顯示器 Screen class Screen extends Component { static defaultProps = {showContent:"無內容"} render () { const showContent = this.props.showContent return ( <div className='screen'>{showContent}</div> ) } }