ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript-确保组件只能是特定父组件的子组件

2019-11-08 07:35:21  阅读:170  来源: 互联网

标签:reactjs javascript


基本上,我希望能够定义一个组件列表,该列表可以在组件层次结构中的“子组件”的紧上方.有没有编程的方式来检查这一点?

该列表基本上是一个类数组,例如

const allowed_parents  = [Parent1, Parent2, Parent3];

接着

<UnListedParent>
  .
  .
  .
  <Child />
</UnListedParent>

应该抛出一个错误

解决方法:

您不能使用任何已知的公共React API从子级直接访问父级.

当然,有“ hacky”方式,例如,通过React.Children.map和React.cloneElement以编程方式在父级上创建createRef并将其传递给子级,但这是一个糟糕的设计,我不打算这样做.甚至将其发布在此处,而不与该代码关联:D

我认为,一种更好的方法可以更好地与React原理和单向自上而下的流程保持一致,那就是结合使用HigherOrderComponent包装的“允许的父母”,将一个特定的标志传递给他们“允许”的孩子,然后签入该子项是否存在标志,否则出错.

大约可以达到this

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Child = ({ isAllowed }) => {
  if (!isAllowed) {
    throw new Error("We are not allowed!");
  }

  return <div>An allowed child.</div>;
};

const allowParentHOC = Wrapper => {
  return ({ children, ...props }) => {
    return (
      <Wrapper {...props}>
        {React.Children.map(children, child =>
          React.cloneElement(child, {
            isAllowed: true
          })
        )}
      </Wrapper>
    );
  };
};

const Parent1 = allowParentHOC(props => <div {...props} />);
const Parent2 = allowParentHOC(props => <div {...props} />);

const UnListedParent = ({ children }) => children;

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  componentDidCatch(error, info) {
    this.setState({ hasError: true, info });
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return (
        <>
          <h1>This Child was not well put :(</h1>
          <pre>{JSON.stringify(this.state.info, null, 2)}</pre>
        </>
      );
    }
    return this.props.children;
  }
}

class App extends React.Component {
  state = {
    isUnAllowedParentShown: false
  };

  handleToggle = () =>
    this.setState(({ isUnAllowedParentShown }) => ({
      isUnAllowedParentShown: !isUnAllowedParentShown
    }));

  render() {
    return (
      <>
        <button onClick={this.handleToggle}>Toggle Versions</button>
        {this.state.isUnAllowedParentShown ? (
          <UnListedParent>
            <Child />
          </UnListedParent>
        ) : (
          <>
            <Parent1>
              <Child />
            </Parent1>
            <Parent2>
              <Child />
            </Parent2>
          </>
        )}
      </>
    );
  }
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(
  <ErrorBoundary>
    <App />
  </ErrorBoundary>,
  rootElement
);

标签:reactjs,javascript
来源: https://codeday.me/bug/20191108/2006576.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有