父组件给子组件传值,通过属性的方式传值
子组件如果是类
import React, { Component } from 'react';
// 1.类子组件
class ChildCpn1 extends Component {
constructor(props) {
super();
this.props = props;
}
render() {
const { name, age, height } = this.props;
return (
<div>
<h2>我是class的组件</h2>
<p>展示父组件传递过来的数据: {name + " " + age + " " + height}</p>
</div>
)
}
}
export default class App extends Component {
render() {
return (
<div>
<ChildCpn1 name="why" age="18" height="1.88" />
</div>
)
}
}
子组件如果是函数
function ChildCpn2(props){
const {name,age,height} = props;
return (
<div>
<h2>function组件哈</h2>
<p>展示父组件传递过来的数据:{name + " "+ age+ " "+height}</p>
</div>
)
}
参数验证,需要导入
import PropTypes from 'prop-types';
用法如下
ChildCpn1.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
height: PropTypes.number
}
某个属性必须的设置用法如下
requiredFunc: PropTypes.func.isRequired
设置属性的默认值为如下用法
ChildCpn1.defaultProps = {
name: "王小波",
age: 40,
height: 1.92
}
子组件传递父组件
在Vue中是通过自定义事件来完成的,但是在React中同样是通过props传递信息,只是让父组件给子组件传递一个回调函数,子组件中调用这个回调函数即可。
function CounterButton(props){
const {operate,btnClick} = props;
return <button onClick={btnClick}>{operate}</button>
}
export default class ParentButton extends Component {
constructor(props){
super(props)
this.state = {
counter: 0
}
}
changeCounter(count){
this.setState({
counter: this.state.counter+count
})
}
render(){
return (
<div>
<h2>子组件向父组件传值的操作:{this.state.counter}</h2>
<CounterButton operate="+1" btnClick={e=>this.changeCounter(1)}></CounterButton>
<CounterButton operate="-1" btnClick={e=>this.changeCounter(-1)}> </CounterButton>
</div>
)
}
}
function ChildCpn2(props){
const {name,age,height} = props;
return (
<div>
<h2>function组件哈</h2>
<p>展示子组件传递过来的数据:{name + " "+ age+ " "+height}</p>
</div>
)
}