Reactjs React js中PropTypes的用法
我试图通过“道具”将数据从父组件传递到子组件 为此,我定义了:Reactjs React js中PropTypes的用法,reactjs,react-props,Reactjs,React Props,我试图通过“道具”将数据从父组件传递到子组件 为此,我定义了: <Sidebar name="Dave" /> 在子组件中 现在我得到: 现在,我明白了我需要使用PropTypes进行验证 我做的下一件事是定义: SideBar.PropTypes = { name: PropTypes.string, } 据我所知,它应该足以修复错误, 有人能帮我弄清楚吗 my Child组件的代码:sideBar.jsx: import PropTypes from '
<Sidebar name="Dave" />
在子组件中
现在我得到:
现在,我明白了我需要使用PropTypes进行验证
我做的下一件事是定义:
SideBar.PropTypes = {
name: PropTypes.string,
}
据我所知,它应该足以修复错误,
有人能帮我弄清楚吗
my Child组件的代码:sideBar.jsx:
import PropTypes from 'prop-types'
class Sidebar extends React.Component {
constructor(props) {
super(props)
}
state = {
message: this.props.value,
}
render() {
return <div>hello {this.state.message}</div>
}
}
export default Sidebar
Sidebar.PropTypes = {
name: PropTypes.string,
}
从“道具类型”导入道具类型
类侧栏扩展了React.Component{
建造师(道具){
超级(道具)
}
状态={
消息:this.props.value,
}
render(){
返回hello{this.state.message}
}
}
导出默认边栏
侧栏.PropTypes={
名称:PropTypes.string,
}
我的父组件代码:Homepage.jsx:
class Homepage extends Component {
constructor(props) {
super(props)
}
render() {
return (
<>
<Sidebar name='Dave' />
</>
)
}
}
export default Homepage
类主页扩展组件{
建造师(道具){
超级(道具)
}
render(){
返回(
)
}
}
导出默认主页
您传递的道具是“name”,但您在子组件中使用的道具是“value”,因此我认为您应该更改您的状态:
state = {
message: this.props.name,
}
您将消息放在proptypes中,但在实际实现中使用值。
state = {
message: this.props.name,
}