यह शायद सबसे समझ में आता है एक संपत्ति के रूप में यह पारित करने के लिए, लेकिन अगर आप वास्तव में यह प्रोग्राम के रूप में प्राप्त करने की आवश्यकता है, और से अंदर घटक, आप घटक माउंट करने के लिए इंतजार कर सकते हैं, इसके डोम नोड लगता है , और उसके बाद अपने माता-पिता को देखो।
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
तर्क द्वारा निर्दिष्ट संपत्ति पर मूल कंटेनर आईडी निर्दिष्ट करने वाला एक अतिरिक्त प्रोप।
आप उन्हें 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
तुम बस document.getElementById उपयोग नहीं कर सकते ('रेडियल -1')? –
मेरे पास इस घटक के लिए अलग-अलग आईडी –
पास 'radials-1' प्रोप के रूप में एकाधिक प्रस्तुतकर्ता हैं? –