子组件向父组件传值
子组件
import React , { Component } from 'react';
import { Input } from 'antd';
import './SearchBox.less';
class SearchBox extends Component{
constructor(props){
super(props);
}
componentDidMount(){
}
inpuValueChange=(event)=>{
this.props.InputQuery(event.target.value) // 将输入框获取到的内容传给父组件,**注意名字(InputQuery)**
}
render(){
return <div className='searchInputCon'>
<Input placeholder="请输入搜索内容" onChange = { this.inpuValueChange }/>
</div>
}
}
export default SearchBox;
父组件
import React , { Component } from 'react';
import HotKey from '../../components/HotKey/HotKey';
import SearchBox from '../../components/SearchBox/SearchBox';
class Search extends Component {
Query=(data)=>{
console.log('父组件接收的数据');
console.log(data);
}
render(){
return(
<>
<SearchBox InputQuery= {this.Query}/> //在父组件中接收子组件传递过来的数据 **注意名字(InputQuery)**
<HotKey/>
<div className='searchResult'>
</div>
</>
)
}
}
export default Search;
结果
父组件像子组件传值 //简化代码,删除了业务逻辑,主要看传值
父组件
import React , { Component } from 'react';
import SingerView from '../../components/singerView/singerView';
import { getSingerList } from '../../api/singer';
import Singer from '../../common/singer'
class SingerPage extends Component {
constructor(props) {
super(props);
this.state = {
isLoading:true
};
}
componentDidMount(){
this._getSingerList();
}
render(){
return(
<div>
{
this.state.isLoading
?<div>加载中</div>
: <SingerView singerList={ this.state.singerList } /> // 向子组件传值
}
</div>
)
}
}
export default SingerPage;
子组件
import React , { Component } from 'react';
import SingerTel from '../../components/singerTel/singerTel'
import './singerView.less';
class singerView extends Component{
constructor(props) {
super(props);
}
componentDidMount(){
console.log(this.props.singerList)
}
render(){
let singerList = this.props.singerList; //子组件通过props 进行接收
return(
<ul className='singerCon'>
{
singerList.map((item,index)=>{
return <li key={ item+index }>
<h4>{ item.tittle }</h4>
<SingerTel singerObj = { item }/>
</li>
})
}
</ul>
)
}
}
export default singerView;