React 父传子
先展示父组件
import React, { Component } from 'react'
import Banner from "../Banner/Banner"
export default class Header extends Component {
constructor(props){
super(props);
this.state={
title:'我是标题'
}
}
render() {
const{title} = this.state
return (
<div>
<Banner name="whycodery" age="18" height="1.88"/> //子组件的复用
<Banner name="kebo" age="18" height="2.3"/>
<h3 title={title}>我是标题</h3>
</div>
)
}
}
再展示子组件
import React, { Component } from 'react'
export default class Banner extends Component {
render() {
const {name,age,height} = this.props //通过this.props解构拿到数据
return (
<div>
<span>
子组件展示的信息
姓名:{name},
年龄:{age},
身高:{height},
</span>
</div>
)
}
}
通过this.props解构后拿到name,age,height的数据。
下面是通过函数式组件:父传子
import React from 'react' export default function Hanshu(props) { const {name,age,height} = props return ( <div> 你好,我叫{name},今年{age}岁,{height}cm。 </div> ) }
不需要this。直接传入props。解构后拿到数据
父传子的参数验证:propTypes
Banner.propTypes = {
name:PropTypes.string.isRequired, //加上isRequired说明必须传的值
age:PropTypes.number,
names:PropTypes.array
}
不传值的情况,展示默认值 defaultProps
人,一定不能懒,懒习惯了,稍微努力一下便以为是在拼命。

浙公网安备 33010602011771号