【问题标题】:How can I provide the PropTypes for a inner, nested component?如何为内部嵌套组件提供 PropTypes?
【发布时间】:2022-01-12 16:42:25
【问题描述】:

我有一个相当复杂的组件,所以我从嵌套组件构建它。简化:

export function BlockProvideFeedback(props) {  
  const handleSelect = (event) => console.log(event);

  const Form = (props) => (
    <>
      <RadioList selected={props.selected} />
      <Button onClick={handleSelect} />
    </>
  );

  const Message = () => (
    <p>Thanks for the feedback</p>
  );

  if (props.feedbackStatus == 'agreed') {
    return(<Form selected='done'/>);
  if (props.feedbackStatus == 'pending') {
    return(<Form selected='needswork'/>);
  } else {
    return(<Message/>);
  }
};

BlockProvideFeedback.propTypes = {
  feedbackStatus: PropTypes.string.isRequired,
};

linter 理所当然地指出 props.selected in Form(props) 需要 propTypes。但我不知道在哪里以及如何提供它们。 道具验证中缺少'selected'

我尝试了显而易见的:

BlockProvideFeedback().Form.propTypes { //... }

但这会引发错误,因为我在没有适当的上下文、道具、提供者等的情况下实例化组件(通过调用函数)。

如何将 selected 放入我的嵌套组件的 props 验证中?

或者我可能在做其他严重错误的事情:例如,我的整个嵌套设置可能是非反应式的,以至于像 linter 这样的工具会在无法解决它的情况下失败?

【问题讨论】:

  • 请问您为什么要在 BlockProvideFeedback 之一中声明 FormMessage 组件,而不是将它们作为单独的组件?
  • @secan:两个原因,真的。首先是在我更复杂的实现中,&lt;Form&gt; 使用父 &lt;BlockProvideFeedback&gt; 状态和助手。在示例中,我用handleSelect 表示了这一点。如果它们是单独的组件,我要么需要提取该状态和此类方法,要么将它们传递出去。其次:它们不是真正的组件:从不重复使用,从不导出等。从概念上讲,它们不是独立的东西,真的。
  • 我会尝试在您定义 Form 之后立即添加 Form.propTypes = { //... }
  • 但是,如果 FormBlockProvideFeedback 中“生死攸关”并且它没有在其他任何地方重用,则不需要对其 props 进行类型检查:不可能发生另一个组件使用它并且尝试向selected props 发送一个号码。
  • @secan 很好的论据。按照这种推理,linter 是完全错误的,应该在那里被忽略。有道理。

标签: javascript reactjs react-proptypes


【解决方案1】:

如果FormMessage 不打算共享和重用,我会将它们转换为“渲染函数”;类似:

export function BlockProvideFeedback(props) {  
  const handleSelect = (event) => console.log(event);

  const renderForm = (selectedVal) => (
    <>
      <RadioList selected={selectedVal} />
      <Button onClick={handleSelect} />
    </>
  );

  const renderMessage = () => (
    <p>Thanks for the feedback</p>
  );

  if (props.feedbackStatus == 'agreed') {
    return renderForm('done');
  if (props.feedbackStatus == 'pending') {
    return renderForm('needswork');
  } else {
    return renderMessage();
  }
};

BlockProvideFeedback.propTypes = {
  feedbackStatus: PropTypes.string.isRequired,
};

我知道,这并不能真正回答您的问题,但在我看来,这种情况可能是一种“XY 问题”。

【讨论】:

  • 感谢您的建议。我知道我的问题的 XY 性,因此是最后一个问题段落。
猜你喜欢
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 2011-02-10
  • 2014-11-12
  • 2017-06-15
  • 2019-10-13
相关资源
最近更新 更多