React way to create value and pass the components

In this article we learn to create components, two forms of the components, and how to communicate directly in the component.

Two ways to create forms

1. There are two components to create forms, one form of the function, one is in the form of classes, specifically how to operate?
In src New under components folder, then the new CompType.js , specific code as follows:

import React from 'react';

//  函数类型的组件
export function Welcome1() {
    return (
        <div>
        Welcome1
        </div>
    )
}

// 基于类的组件
export class Welcome2 extends React.Component{
    render(){
      return <div>Welcome2</div>
    }
}

2. Then src -> index.js import component, reuse, specific code as follows:

import { Welcome1, Welcome2 } from './components/CompType'

function App() {
  return (
    <div>
      {/* 使用其他组件 */}
      <Welcome1></Welcome1>
      <Welcome2></Welcome2> 
    </div>
  );
}

Compare:

If a component based only props render the page, not inside the State , we can use the form to achieve the function of the components ( Hooks arrival will change the status quo)

props property transfer

According to the above example, if I want to give components Welcome1 and components Welcome2 add properties, how I want to pass it, please continue to read
1. Modify CompType.js two forms of assembly code is as follows:

//  函数类型的组件
export function Welcome1(props) {
    return (
        <div>
        Welcome1,{props.type}
        </div>
    )
}

// 基于类的组件
export class Welcome2 extends React.Component{
    render(){
    return <div>Welcome2,{this.props.type}</div>

    }
}

note:

Class-based component props when a property value, to increase the current this instance

2. continue to modify src -> index.js embodiment of the import component, as follows:

function App() {
  return (
    <div>
     {/* 使用其他组件 */}
      <Welcome1 type="function"></Welcome1>
      <Welcome2 type="class"></Welcome2>
    </div>
  );
}

note:

Passed in this case props are read-only attribute can not be modified, the unidirectional data flow

Guess you like

Origin www.cnblogs.com/-muzi/p/11964732.html