1.父传子(比起vue传值更简单)
- 父组件里面通过自定义属性向子组件传值,在子组件通过this.props.自定义属性接收
2.子传父
- 父子组件通信不仅可以传值,还可以传递方法,父组件将更新数据的方法拿给子组件使用,子组件将自身的数据传入这个方法并调用,以此来改变父组件的数据。
父组件
import React,{Component}from 'react';
import './home.less';
import Child from '../../components/child/child'
class Home extends Component{
constructor(props){
super(props)
this.state={
account:'',
passWord:'',
message:"i am from parent",
name:'父组件值'
}
}
Foo=(data)=> {
this.setState({
name: data
});
}
render () {
return (
<div className="home">
<div>
<Child txt={this.state.message} data={this.Foo}></Child>
<p>{this.state.name}1</p>
</div>
<footer>
<div className='foot'>概述</div>
<div className='foot'>概述</div>
<div className='foot'>概述</div>
<div className='foot'>概述</div>
</footer>
</div>
)
}
}
export default Home;
子组件
import React,{Component}from 'react';
import './child.less';
import {Button} from 'antd-mobile'
class Child extends Component{
constructor(poprs){
super(poprs)
}
handleClick = () => {
this.props.data("子组件传给父组件的值");
}
render(){
return(
<div>
<Button type='primary'>子组件</Button>
<p>父组件传过来的值:{this.props.txt}</p>
<Button onClick={this.handleClick}>子组件改变父组件</Button>
</div>
)
}
}
export default Child;
3.效果