溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Props屬性的設(shè)置方法

發(fā)布時(shí)間:2020-08-26 10:29:25 來源:億速云 閱讀:225 作者:小新 欄目:web開發(fā)

Props屬性的設(shè)置方法?這個(gè)問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個(gè)問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!

Props屬性設(shè)置的方法:Props屬性是組件自身的屬性,負(fù)責(zé)傳遞消息,可以通過static defaultProps格式來設(shè)置默認(rèn)屬性,static propTypes格式來設(shè)置屬性的格式

Props屬性的設(shè)置方法

Props(屬性)

是組件自身的屬性,props中的屬性與組件屬性一一對(duì)應(yīng)。負(fù)責(zé)傳遞信息

1 父組件向子組件傳遞數(shù)據(jù)

//定義webName組件,負(fù)責(zé)輸出名字
var webName = React.createClass({
  render : function() {
    return <h2>{this.props.webname} </h2>;
  }
})
//定義webLink組件,負(fù)責(zé)跳轉(zhuǎn)鏈接
var webLink = React.createClass({
  render : function() {
    return <a href={this.props.weblink}>{this.props.weblink}</a>
  }
})
 
var webShow = React.createClass({
  render : function(){
    <div>
      <webName webname={this.props.webname}/>
      <webLink weblink={this.props.weblink}/>
    </div>
  }
})
 
//渲染
ReactDom.render{
  return function() {
    <webShow webname = "hellp" weblink = "www.baidu.com" />,
      document.getElementById("container")
  }
}

設(shè)置默認(rèn)屬性

通過 static defaultProps = {} 這種固定的格式來給一個(gè)組件添加默認(rèn)屬性

export default class MyView extends Component {
  static defaultProps = {
    age: 12,
    sex: '男'
  }
 
  render() {
    return <Text
        style={{backgroundColor: 'cyan'}}>
      你好{this.props.name}{'\n'}年齡{this.props.age}{'\n'}性別{this.props.sex}
    </Text>
  }
}

屬性檢查

通過 static propTypes = {} 這種固定格式來設(shè)置屬性的格式,比如說我們將 age 設(shè)置為 number 類型

var title = React.createClass({
  propTypes={
    //title類型必須是字符串
    title : React.PropTypes.string.isRequired
  },
  render : function() {
    return <h2>{this.props.title}</h2>
  }
})

延展操作符 ... 是 ES6 語法的新特性。...this.porps,一種語法,將父組件中全部屬性復(fù)制給子組件

2 父組件向子組件傳遞調(diào)用函數(shù),用來通知父組件消息。

3 用來作為子組件邏輯判斷的標(biāo)示,渲染的樣式等

4 children,不是跟組件對(duì)應(yīng)的屬性,表示組件所有子節(jié)點(diǎn)。

//定義webName組件,負(fù)責(zé)輸出名字
var listCompont = React.createClass({
  render : function() {
    return
    <ul>
      {
        /**
         * 列表項(xiàng)內(nèi)容不固定,需要在創(chuàng)建模版時(shí)確定。利用this.props.children傳遞顯示內(nèi)容
         * 獲取到內(nèi)容后,需要遍歷children,逐項(xiàng)設(shè)置。利用React.Children.map方法
         **/
 
        React.Children.map(this.props.children,function(child) {
            //child是遍歷得到父組件子節(jié)點(diǎn)
            return <li>{child}</li>;
        })
      }
    </ul>;
  }
})
//渲染
ReactDom.render{
  {
    <listCompont>
      <h2>hello</h2>
      <a href="link">"www.baidu.com"</a>
    </listCompont>
  },
document.getElementById("container")
}

感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)Props屬性的設(shè)置方法大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI