3-1如何定义一个组件,以及在父组件中的使用
//如果要使用组件,在src下面新建一个components/Title.js
import React from 'react'
class Title extends React.Component{
constructor(props){
super(props)
}
render(){
return(
<h1>{this.props.msg}</h1>
)
}
}
export default Title;
export default Header;
//在App.js中导入组件
import Title from './components/Title'
//在App.js中使用
<Title/>
3-2父组件给子组件传参
//父组件
import React from 'react';
import Title from './components/Title'
class App extends React.Component{
constructor(props){
super(props);
this.state={
msg:"hello world"
}
}
render(){
return(
<div>
<Title
//1.子组件的属性接收父组件传递过来的方法
deleteItem={this.handleDelete.bind(this)}
msg={this.state.msg}></Title>
</div>
)
}
handleDelete(id){
console.log(id)
}
}
export default App;
//子组件
import React from 'react'
class Title extends React.Component{
constructor(props){
super(props)
}
render(){
return(
<h1 onClick={this.handleClick.bind(this,'1123')}>{this.props.msg}</h1>
)
}
handleClick=(id)=>{
//2.子组件调用方法,向父组件传参
this.props.deleteItem(id)
}
}
export default Title;
3-3父组件中发送请求之后向子组件传值,在子组件中遍历渲染数据
//父组件
import React from 'react';
import Delete from './components/Delete'
class App extends React.Component{
constructor(props){
super(props);
this.state={
msg:"hello world",
playlists:[]
}
}
render() {
return(
<div> //父组件使用属性向子组件传值
<Delete content={this.state.playlists}></Delete> //自定义属性content传参
</div>
)
}
//发送请求 挂载到原型上
componentDidMount(){
var url='https://music.aityp.com/top/playlist?cat=华语'
this.$http.get(url).then(res=>{
var playlists=res.data.playlists;
this.setState({
playlists
})
})
}
}
export default App;
//子组件通过this.props使用数据
import React from 'react'
class Delete extends React.Component{
constructor(props){
super(props)
}
render() {
return(
<div>
{this.props.content.map(item=>{ //通过this.props接收传过来的参数
return(<div key={item.id}>
<p>{item.name}</p>
</div>)
})}
</div>
)
}
}
export default Delete