gpt4 book ai didi

dom - React,获取组件内绑定(bind)的父dom元素名称

转载 作者:行者123 更新时间:2023-12-03 13:02:32 24 4
gpt4 key购买 nike

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

所以如果我的渲染是这样的:

ReactDOM.render(
<RadialsDisplay data={imagedata}/>,
document.getElementById('radials-1')
);

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

最佳答案

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

这是一个例子:

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

<小时/>

如果您经常这样做,或者想要变得真正奇特,您可以使用更高阶的组件:

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 的参数并返回一个新函数。该函数可以将组件类型作为其唯一参数,并返回高阶组件。渲染时,新组件将渲染传递的组件及其所有原始 Prop ,以及在 property 参数指定的属性上指定父容器 ID 的附加 Prop 。

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

@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

关于dom - React,获取组件内绑定(bind)的父dom元素名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32855077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com