Home > Article > Web Front-end > What is a subcomponent in react?
In react, a certain piece of code is encapsulated into a component, and this component is introduced in another component. Then the file that introduces the encapsulated component is called the parent component, and the introduced component is called the child component. .
The operating environment of this article: windows10 system, react16, thinkpad t480 computer.
Recommendation: "react video tutorial"
Sometimes we often can’t tell what is a parent component and what is a child component. Now let’s talk briefly: we encapsulate a certain piece of code into a component, and this component is introduced in another component. The file that introduces the encapsulated component is called the parent component, and the imported component is called the child component.
Directly call the method of the subcomponent in react (non-props method)
We all know that in react, if you want to call the method of the subcomponent in the parent component, usually We will define a method in the parent component and transfer it to the child component as props, and then execute the method to get the parameters returned by the child component to achieve our purpose.
Obviously, this execution needs to be actively triggered.
Is there a way where the method is defined in the child component and can be called directly in the parent component?
The answer is yes.
上码
import React, {Component} from "react"; import { Button } from "antd"; //父组件 export default class Parent extends Component { render() { return( <div> <p>这是父组件</p> <Child triggerRef={this.bindRef} /> <Button type="primary" onClick={this.btnClick} >click</Button> </div> ) } bindRef = ref => { this.child = ref } btnClick = () => { this.child.getValuefromChild() } } //子组件 class Child extends Component { componentDidMount(){ this.props.triggerRef(this) } //这是子组件的方法 getValuefromChild = () => console.log("this is child value.") render() { return <div>这是子组件</div> } }
The above is the detailed content of What is a subcomponent in react?. For more information, please follow other related articles on the PHP Chinese website!