首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >React,在组件中获取绑定的父dom元素名称

React,在组件中获取绑定的父dom元素名称
EN

Stack Overflow用户
提问于 2015-09-30 06:57:17
回答 1查看 67.9K关注 0票数 28

在我的组件中,我如何访问它嵌套在其中的父组件的名称?

因此,如果我的渲染是这样的:

代码语言:javascript
复制
ReactDOM.render(
      <RadialsDisplay data={imagedata}/>,
      document.getElementById('radials-1')
);

如何从组件本身中检索id名称#radials-1

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-30 08:40:46

将其作为属性传递可能是最有意义的,但如果确实需要以编程方式获取它,则可以从组件内部等待组件挂载,找到它的DOM节点,然后查看它的父节点。

下面是一个例子:

代码语言:javascript
复制
class Application extends React.Component {
  constructor() {
    super();
    this.state = { containerId: "" };
  }

  componentDidMount() {
    this.setState({
      containerId: ReactDOM.findDOMNode(this).parentNode.getAttribute("id")
    });
  }

  render() {
    return <div>My container's ID is: {this.state.containerId}</div>;
  }
}

ReactDOM.render(<Application />, document.getElementById("react-app-container"));

工作演示:https://jsbin.com/yayepa/1/edit?html,js,output

如果你经常这样做,或者想要变得更花哨,你可以使用一个更高阶的组件:

代码语言:javascript
复制
class ContainerIdDetector extends React.Component {
  constructor() {
    super();
    this.state = { containerId: "" };
  }

  componentDidMount() {
    this.setState({
      containerId: ReactDOM.findDOMNode(this).parentNode.getAttribute("id")
    });
  }

  render() {
    if (!this.state.containerId) {
      return <span />;
    } else {
      return React.cloneElement(
        React.Children.only(this.props.children),
        { [this.props.property]: this.state.containerId }
      );
    }
  }
}

ContainerIdDetector.propTypes = {
  property: React.PropTypes.string.isRequired
}

// Takes an optional property name `property` and returns a function. This
// returned function takes a component class and returns a new one
// that, when rendered, automatically receives the ID of its parent
// DOM node on the property identified by `property`.
function withContainerId(property = "containerId") {
  return (Component) => (props) =>
    <ContainerIdDetector property={property}>
      <Component {...props} />
    </ContainerIdDetector>
}

在这里,withContainerId是一个函数,它接受一个名为property的参数并返回一个新函数。此函数可以将一个组件类型作为其唯一参数,并返回一个更高阶的组件。呈现时,新组件将呈现传递的组件及其所有原始道具,以及在property参数指定的属性上指定父容器ID的附加道具。

如果您愿意,您可以将它们与ES7装饰器(如当前实现的)一起使用,或者通过常规函数调用使用它们:

代码语言:javascript
复制
@withContainerId()
class Application extends React.Component {
  render() {
    return <div>My containers ID is: {this.props.containerId}</div>;
  }
}

// or, if you don't use decorators:
//
// Application = withContainerId()(Application);

ReactDOM.render(<Application />, document.getElementById("react-app-container"));

工作演示:https://jsbin.com/zozumi/edit?html,js,output

票数 51
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32855077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档