前文回顧
riot.js教程【四】Mixins、HTML內嵌表達式
riot.js教程【三】訪問DOM元素、使用jquery、mount輸入參數、riotjs標籤的生命週期;
riot.js教程【二】組件撰寫準則、預處理器、標籤樣式和裝配方法;
riot.js教程【一】簡介;html
讓咱們定義一個父標籤account,一個子標籤subscriptionjquery
<account> <subscription plan={ opts.plan } show_details="true" /> </account> <subscription> <h3>{ opts.plan.name }</h3> // Get JS handle to options var plan = opts.plan, show_details = opts.show_details // access to the parent tag var parent = this.parent </subscription>
注意:show_details的命名方式,這裏不能寫成駝峯式的名字,由於瀏覽器解析標籤的時候會把大寫轉成小寫瀏覽器
接下來咱們把account標籤添加到頁面的body中dom
<body> <account></account> </body> <script> riot.mount('account', { plan: { name: 'small', term: 'monthly' } }) </script>
父標籤的參數是經過riot.mount方法傳遞的,子標籤的參數是經過標籤屬性傳遞過去的ide
注意:嵌套的標籤老是在父標籤內部聲明,定義;this
咱們先定義一個my-tag標籤code
<my-tag> <p>Hello <yield/></p> this.text = 'world' </my-tag>
注意:這裏有一個yield佔位符,咱們稍後再講它orm
如今咱們在頁面上使用這個標籤htm
<my-tag> <b>{ text }</b> </my-tag>
那麼他渲染出來以後,是以下這個樣子的:對象
<my-tag> <p>Hello <b>world</b><p> </my-tag>
你看到了嗎?yield佔位符輸出的,實際上是text變量
這就是在標籤內嵌入HTML代碼
當元素具有ref屬性的時候,
這個元素會被連接到this.refs上,
這樣你就能夠很方便的用JS訪問到它
<login> <form ref="login" onsubmit={ submit }> <input ref="username"> <input ref="password"> <button ref="submit"> </form> // grab above HTML elements submit(e) { var form = this.refs.login, username = this.refs.username.value, password = this.refs.password.value, button = this.refs.submit } </login>
注意,這個指向的操做,是在mount事件被觸發前完成的,因此你能夠在mount事件中訪問到this.refs
DOM事件能夠直接和riotjs標籤內的方法綁定,示例以下:
<login> <form onsubmit={ submit }> </form> // this method is called when above form is submitted submit(e) { } </login>
只要事件名以on開頭的,好比:onclick, onsubmit, oninput,均可以直接綁定方法
這類事件也能夠直接綁定一句表達式,以下:
<form onsubmit={ condition ? method_a : method_b }>
在事件方法內,this指代本標籤實例,方法執行完以後,會立刻執行this.update()事件,
若是你在方法內部,使用了event.preventUpdate,那麼方法執行完以後,就不會執行this.update()事件;
方法的第一個參數就是標準的event對象
你可使用標籤條件來決定是否須要顯示一個標籤,以下:
<div if={ is_premium }> <p>This is for premium users only</p> </div>
注意,標籤條件的值能夠是一個變量,也能夠是一個表達式
除了if以外,還可使用show和hide來決定是否顯示一個標籤
show – 當值是true的時候,至關於 style="display: ''"
hide – 當值是true的時候,至關於 style="display: none"
if – 當值是true的時候,會把該標籤加入到DOM元素中,是false的時候,不會把標籤加入到dom元素中