在我的组件中,如何访问嵌套在其中的父组件的名称?
因此,如果我的渲染是这样的:
ReactDOM.render( <RadialsDisplay data={imagedata}/>, document.getElementById('radials-1') );
如何从组件本身中检索id名称#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并返回一个新函数。此函数可以将组件类型作为其唯一参数,并返回高阶组件。渲染时,新组件将渲染 传递的 组件,包括其所有原始道具,以及在property参数指定的属性上指定父容器ID的其他道具。
withContainerId
property
如果需要,可以将它们与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