反应 - 检查道具是否存在

lsi*_*tti 14 javascript reactjs

我在互联网上搜索了这个问题的答案,但我没找到.所以我在这里发帖子.

我有一个父组件(App)和一个子组件(Child).App组件的状态包含一些数据,如下所示:

class App extends Component {
    constructor() {
        super()

        this.state = {
            currentOrganization: {
                name: 'name',
                email: 'email'
            }
        }
        render() {
            return (
                <Child data={this.state.currentOrganization} />
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的Child组件中,我有一个表单:

class Child extends Component {
    constructor() {
        super()

        this.state = {
            formData: {
                name: '',
                email: '',
            }
        }
    }

        render() {
            return (
            <Form ... />
          )
        }
    }
Run Code Online (Sandbox Code Playgroud)

根据React文档,表单通常应该具有包含与表单的每个元素相对应的属性的状态.我的Child组件中的表单必须具有currentOrganization的数据(如App组件中所示)预先填充到自身中.

为了实现这一点,我必须将Child的状态设置为从其父级接收的道具.

检查我的Child组件是否收到了更新自己状态所需的道具的最佳方法是什么?

Raf*_*yan 22

您可以将默认道具分配给组件.

class Child extends Component {
  constructor(props) {
    super(props);

    this.state = {
      formData: {
        name: props.name,
        email: props.email,
      }
    }
  }

  render() {
    return (
      <Form ... />
    )
  }
}

Child.defaultProps = {
  name: '',
  email: '',
};
Run Code Online (Sandbox Code Playgroud)

PS props是JS对象所以你可以检查这样的属性 "prop_name" in this.props // true|false

  • +1在构造函数中使用`props.xxx`而不是`this.props`并使用空字符串作为输入值而不是null. (2认同)
  • 也可以这样写:`const {name ='',email =''} = props`,然后在* constructor *中`this.state.formData({name,email})`。 (2认同)