将其作为属性传递可能是最有意义的,但是如果您really需要以编程方式获取它,并且从inside组件,你可以等待组件挂载,找到它的 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,输出 https://jsbin.com/yayepa/1/edit?html,js,output
如果你经常这样做,或者想成为really奇特的是,您可以利用更高阶的组件:
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>
}
Here, withContainerId
是一个带有参数的函数property
并返回一个新函数。该函数可以将组件类型作为其唯一参数,并返回高阶组件。渲染时,新组件将渲染passed组件及其所有原始 props,加上一个附加 prop,在由 指定的属性上指定父容器的 IDproperty
争论。
如果您愿意,您可以将它们与 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,输出 https://jsbin.com/zozumi/edit?html,js,output