[英]ReactJs How to access child components refs from parent
如何訪問父項中的子項的引用以在父函數中對它們執行某些操作?
class Parent extends Component {
someFunction(){
// how to access h1 element of child in here ??
}
render() {
return (
<Child />
);
}
}
class Child extends Component {
render() {
return (
<h1 ref="hello">Hello</h1>
);
}
}
要添加Shubham的答案,必須在父級內的componentDidMount()內訪問子引用。 就像是:
class Parent extends React.Component {
componentDidMount(){
var elem1 = this.refs.child1.refs.childRefName;
}
return (
<View>
<Child1 ref='child1'/>
<Child2 />
<Child3 />
</View>
);
}
您可以通過為子元素提供ref並訪問子元素來訪問子引用,如ReactDOM.findDOMNode(this.refs.child.refs.hello)
在您的情況下,子組件不以您需要更改的大寫字母開頭。
class App extends React.Component { componentDidMount() { console.log(ReactDOM.findDOMNode(this.refs.child.refs.hello)); } render() { return ( <Child ref="child"/> ); } } class Child extends React.Component { render() { return ( <h1 ref="hello">Hello</h1> ); } } ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <divi id="app"></div>
您還可以使用React.forwardingRef
方法使Child
組件能夠從其父組件接收和定義ref
。
以下是該方法的文檔:
https://reactjs.org/docs/forwarding-refs.html
以下是您可以在代碼中實現它的示例:
const Child = React.forwardRef((_, ref) => (
<h1 ref={ref}>Child Component</h1>
));
function Parent() {
var h1 = React.createRef();
React.useEffect(() => {
console.log(h1.current);
});
return <Child ref={h1} />;
}
https://reactjs.org/docs/forwarding-refs.html
我希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.