我在互联网上搜索了这个问题的答案,但没有找到。因此,我在这里发布我的问题。
我有一个父组件 (App) 和一个子组件 (Child)。 App 组件有一个状态,其中包含一些数据,如下所示:
class App extends Component {
constructor() {
super()
this.state = {
currentOrganization: {
name: 'name',
email: 'email'
}
}
render() {
return (
<Child data={this.state.currentOrganization} />
)
}
}
}
在我的子组件中,我有一个表单:
class Child extends Component {
constructor() {
super()
this.state = {
formData: {
name: '',
email: '',
}
}
}
render() {
return (
<Form ... />
)
}
}
根据 React 文档,表单通常应该有一个状态,其中包含与表单的每个元素相对应的属性。位于我的 Child 组件中的表单必须将 currentOrganization 的数据(如在 App 组件中所见)预填充到自身中。
为了实现这一点,我必须将 Child 的状态设置为它从其父级接收到的 props。
检查我的子组件是否收到更新其自身状态所需的 Prop 的最佳方法是什么?
最佳答案
您可以为组件分配默认 Prop 。
class Child extends Component {
constructor(props) {
super(props);
this.state = {
formData: {
name: props.name,
email: props.email,
}
}
}
render() {
return (
<Form ... />
)
}
}
Child.defaultProps = {
name: '',
email: '',
};
附言
props
是 JS 对象,所以你可以这样检查属性
this.props 中的“prop_name”//true|false
关于javascript - React - 检查 Prop 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46330124/