案例要求:
達到這樣乙個效果
元件拆分:
fromimport react,
from
'react'
import search from
'./components/search/search'
import
import list from
'./components/list/list'
export
default
class
extends
component
getdata
=(items)
=>)}
setfirst=(
)=>)}
setloading=(
)=>
=this
.state
// this.state.setstate()
console.
log(isloading)
this
.setstate()
}seterr
=(errinfo)
=>)}
render()
=this
.state
return
("container"
>
setfirst=
setloading=
seterr=
/>
isfirst=
isloading=
err=
/>
<
/div>)}
}search元件**
import react,
'react'
import axios from
'axios'
export
default
class
search
extends
component}=
this
this
.props.
setfirst()
this
.props.
setloading()
this
.props.
seterr(""
)//每次請求之前把err清空
//2、傳送網路請求
(//如果站的位置就是傳送請求的位置,可以把http://localhost:3000省略
//這裡面只能寫response和error
response=>
, error =>)}
render()
} type=
"text" placeholder=
/>
>搜尋<
/button>
<
/div>
<
/section>)}
}list元件**
import react,
from
'react'
import
'./list.css'
export
default
class
list
extends
component
=this
.props
if(this
.props.isfirst)if(
this
.props.isloading)if(
this
.props.err!=="")
<
/span>
<
/div>
}return
("row"
>
>
>
"head_picture" src=
style=
}>
<
/img>
<
/a>
"card-text"
>
<
/p>
<
/div>)}
)}<
/div>)}
}狀態在操作元件中定義,訊息在傳遞狀態的元件中發布,在使用狀態的元件中訂閱。使用pubsubjs庫實現訊息訂閱。
搜尋框元件**
import react,
from
'react'
import axios from
'axios'
import pubsub from
'pubsub-js'
export
default
class
search
extends
component
}=this
// this.props.setfirst()
// this.props.setloading()
// this.props.seterr("")//每次請求之前把err清空
// //2、傳送網路請求
// axios.get(`http://localhost:3000/api1/search/users?q=$`).then( //如果站的位置就是傳送請求的位置,可以把http://localhost:3000省略
// //這裡面只能寫response和error
// response=>,
// error =>
// )
search=(
)=>}=
this
pubsub.
publish
('state',)
//發布訊息
( response =>)}
, error =>)}
)}render()
} type=
"text" placeholder=
/>
>搜尋<
/button>
<
/div>
<
/section>)}
}展示列表元件**:
import react,
from
'react'
import pubsub from
'pubsub-js'
import
'./list.css'
export
default
class
list
extends
component
componentdidmount()
)}componentwillunmount()
render()
=this
.state
if(this.props.isloading)
if(this.props.err!=="")
}return (
style=
}>
<
/h2>
: items.
map(
(item)
=>
>
>
"head_picture" src=
style=
}>
<
/img>
<
/a>
"card-text"
>
<
/p>
<
/div>)}
)}<
/div>)}
}
react 元件之間的通訊
react推崇的是單向資料流,自上而下進行資料的傳遞,但是由下而上或者不在一條資料流上的元件之間的通訊就會變的複雜。解決通訊問題的方法很多,如果只是父子級關係,父級可以將乙個 函式當作屬性傳遞給子級,子級可以直接呼叫函式從而和父級通訊。元件層級巢狀到比較深,可以使用上下文context來傳遞資訊,這...
vue元件通訊(父子之間,兄弟之間)
1 在父元件中引入需要通訊的子元件import son from components son 2 在父元件的components中註冊該子元件components 3 在父元件的template中使用子元件4 將需要傳遞給子元件的值通過v bind 此處的price則是傳遞給子元件的值5 在對應的...
react父子元件之間通訊
父子元件之間通訊 父傳子通訊 類元件 index.js import react from react import reactdom from react dom reactdom.render document.getelementbyid root import react,from reac...