react 父子组件通信(第一篇)
# react 父子组件通信(第一篇)
在React中,父组件可以通过props向子组件传递数据,但是如果你想让父组件能够调用子组件的方法,或者让子组件向父组件传递数据,就需要使用一些特殊的技巧¹²⁷。
父组件调用子组件的方法:
你可以使用React.createRef()或ref的函数式声明来创建一个引用,然后将这个引用传递给子组件。在子组件中,你可以使用React.forwardRef()来接收这个引用,并将其绑定到一个实例方法上。然后,父组件就可以通过这个引用来调用子组件的方法¹²。
以下是一个示例:
class Child extends React.Component {
myMethod() {
console.log('Child component method');
}
render() {
return <div>Child Component</div>;
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
componentDidMount() {
this.childRef.current.myMethod();
}
render() {
return <Child ref={this.childRef} />;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
在这个示例中,父组件Parent在componentDidMount生命周期方法中调用了子组件Child的myMethod方法。
子组件向父组件传递数据: 子组件可以通过props向父组件传递一个函数,然后在需要的时候调用这个函数,并将数据作为参数传递给这个函数⁷。
以下是一个示例:
class Parent extends React.Component {
handleData(data) {
console.log(data);
}
render() {
return <Child onData={this.handleData} />;
}
}
class Child extends React.Component {
componentDidMount() {
this.props.onData('Data from Child');
}
render() {
return <div>Child Component</div>;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
在这个示例中,子组件Child在componentDidMount生命周期方法中调用了父组件Parent传递的onData方法,并将字符串'Data from Child'作为参数传递给这个方法。
希望这个信息对你有所帮助,如果你有任何其他问题,欢迎随时向我提问。😊
源: 与必应的对话, 2023/11/30
- React父组件调用子组件的方法 - 掘金. https://juejin.cn/post/6977367229960552455.
- react中父组件调用子组件的方法 - CSDN博客. https://blog.csdn.net/qq_36990322/article/details/109858890.
- react函数式组件传值之子传父_react 子传父-CSDN博客. https://blog.csdn.net/w544924116/article/details/119565219.
- React父组件调用子组件的方法-腾讯云开发者社区-腾讯云. https://cloud.tencent.com/developer/article/2041914.
- react函数式组件之---父组件调用子组件实例方法 - 木易锅巴 - 博客园. https://www.cnblogs.com/yxfboke/p/14837279.html.
- 在 React 中如何在组件之间传递数据和事件 - freeCodeCamp.org. https://www.freecodecamp.org/chinese/news/pass-data-between-components-in-react/.
- React 父子组件通信的几种方法 - 掘金. https://juejin.cn/post/7028779975780073485.
- React中子组件如何向父组件传递数据 - 半忧夏 - 博客园. https://www.cnblogs.com/banyouxia/p/12158101.html.
编辑 (opens new window)
上次更新: 2023/12/15, 15:07:46