What is a subcomponent in react?

藏色散人
Release: 2023-01-04 09:37:24
Original
2579 people have browsed it

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. .

What is a subcomponent in react?

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( 
         

这是父组件

) } 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
这是子组件
} }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!