import React, { Component } from 'react'
import PropTypes from 'prop-types'
// 父传子
class Student extends Component {
constructor(props) {
super(props)
}
static propTypes = {
// 限制传入的数据类型为string
msg: PropTypes.string
// 限制必须传值
// msg: PropTypes.string.isRequired
}
// 定义默认的值
static defaultProps = {
msg : "默认值"
}
render() {
return (
<h1>{this.props.msg}</h1>
)
}
}
export default class App9 extends Component {
state = {
msg : "传家宝"
}
render() {
return (
<div>
<Student msg={this.state.msg}></Student>
</div>
)
}
}
React:父传子
于 2022-02-28 11:01:09 首次发布
本文通过一个简单的React应用示例,展示了如何在父子组件间传递数据,包括设置propTypes来验证props的类型,使用defaultProps设定默认props值,以及在组件中接收并渲染props内容。
628

被折叠的 条评论
为什么被折叠?



