ReactJs 如何从父来源访问子公司的链接

如何访问父函数中的子项链接,在父功能中与它们进行操作?


class Parent extends Component {

someFunction//{
// how to access h1 element of child in here ??
}

render// {
return /
<child></child>
/;
}
}



class Child extends Component {
render// {
return /
<h1 ref="hello">Hello</h1>
/;
}
}
已邀请:

三叔

赞同来自:

要添加到Schubham回复,必须在内部提供子链接 componentDidMount// 在父母里面。 有点:


class Parent extends React.Component {
componentDidMount//{
var elem1 = this.refs.child1.refs.childRefName;
}

return /
<view>
<child1 ref="child1"></child1>
<child2></child2>
<child3></child3>
</view>
/;
}

窦买办

赞同来自:

例如,您可以通过向子元素提供引用并访问它来访问子链接,例如访问它
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"></child>
/;
}
}
class Child extends React.Component {
render// {
return /
<h1 ref="hello">Hello</h1>
/;
}
}


ReactDOM.render/<app></app>, document.getElementById/'app'//;



[code]<script src="https://cdnjs.cloudflare.com/a ... gt%3B
<script src="https://cdnjs.cloudflare.com/a ... gt%3B
<divi id="app"></divi>

江南孤鹜

赞同来自:

您也可以使用该方法
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}"></child>;
}


https://reactjs.org/docs/forwarding-refs.html
我希望它会有所帮助。

要回复问题请先登录注册