一 父传子通信-类组件
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 23:28:48
* @LastEditTime: 2022-10-14 23:49:53
*/
import React, { Component } from 'react'
//定义名称需要大写
class ChildCpn extends Component {
// constructor(props) {
// super()
// this.props = props
// }
render() {
const { name, age, height } = this.props
return (
<div>
<h2>子组件展示数据: { name + age + height }</h2>
</div>
)
}
}
export default class App extends Component {
render() {
return (
<div>
<ChildCpn name="测试" age="18" height="1.88"/>
</div>
)
}
}
二 父传子通信-函数组件
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 23:50:26
* @LastEditTime: 2022-10-14 23:53:50
*/
import React from 'react'
function ChildCpn(props) {
const { name, age, height } = props;
return (
<h2>{ name + age + height }</h2>
)
}
export default function App() {
return (
<div>
<ChildCpn name="why" age="18" height="1.88"/>
</div>
)
}
三 父传子通信-属性验证
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 23:50:26
* @LastEditTime: 2022-10-15 00:33:48
*/
import React from 'react'
//引入组件库
import propTypes from 'prop-types';
import { Component } from 'react';
function ChildCpn(props) {
const { name, age, height, names } = props;
return (
<div>
<h2>{ name + age + height }</h2>
<ul>
{
names.map((item) => {
return <li>{item}</li>
})
}
</ul>
</div>
)
}
ChildCpn.propTypes = {
name: propTypes.string.isRequired,
age: propTypes.number,
height: propTypes.number,
names: propTypes.array
}
ChildCpn.defaultProps = {
name: 'test',
age: 120,
height: 2.0,
names: ['xsada','sadasd', 'sadasd'],
}
//或者
class ChildCpn2 extends Component {
static propTypes = {
}
static defaultProps = {
}
}
export default function App() {
return (
<div>
<ChildCpn name="why" age={18} height={1.88} names={['aaa', 'bbb']}/>
<ChildCpn />
</div>
)
}
四 子传父通信-函数传递
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 22:21:24
* @LastEditTime: 2022-10-16 01:15:56
*/
import React, { Component } from 'react'
class CounterButton extends Component {
render() {
const { inCrement } = this.props
return (
<div>
<button onClick={ inCrement }>+1children</button>
</div>
)
}
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
render() {
return (
<div>
<h2>当前计数器: { this.state.counter }</h2>
<button onClick={ e => this.inCrement() }>+1</button>
{/*this.inCrement.bind(this)*/}
<CounterButton inCrement={ e => this.inCrement() }/>
</div>
)
}
inCrement() {
console.log('被调用')
this.setState({
counter: this.state.counter + 1
})
}
}