How to create component hierarchy with React Native?

0

I want to create components with TextInput, the default being my Input component without a mask, and the children will have a mask or some other treatment.

I currently have the default Input that contains only the styles and return the raw text as you type. I also have an Input with CPF / CNPJ mask, and at the time of export I am using an index.js file that only contains these two components and exports them.

index.js

import Input from './Input'
import CpfCnpj from './input-masks/InputCpfCnpj'

export { CpfCnpj }

export default Input

But I'd like to use it this way when you want to use it without masks:

<Input {...this.props} />

And so when you need a mask:

<Input.CpfCnpj {...this.props} />

One way I found was to do this in the index.js

import Input from './Input'
import CpfCnpj from './input-masks/InputCpfCnpj'

Input.CpfCnpj = CpfCnpj

export default Input

I wonder if there is another way, and if this is a good practice?

    
asked by anonymous 02.04.2018 / 15:02

1 answer

0

There are two ways I know of one component "inheriting" the properties of another, which is extending or putting into another.

HERITAGE

Parent component:

import React from 'react';

class GenericForm extends React.Component {
  constructor(props) {
    super(props);

    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChange = e => {
    const target = e.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    this.setState({
      dataForm: { ...this.state.dataForm, [e.target.name]: value}
    });
  }
}
export default GenericForm;

Child component:

class FormLogin extends GenericForm {
  constructor(props) {
    super(props);

    this.state = {
      data: {
        login: '',
        password: ''
      },
      loading: false,
      errors: {}
    };
  }
}

COMPONENT WITHIN COMPONENT

Generic table (style only)

class Table extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <table className={'${this.props.className} Table'}>
        {this.props.children}
      </table>
    )
  }
}

Specific Table: here you can add more styles, methods and more

class TableList extends Component {
  constructor(props) {
    super(props);
  }

  open() {
    // do something
  }

  render() {
    return (
      <Table className={'${this.props.className} TableList' onClick={this.open}}>
        {this.props.children}
      </Table>
    )
  }
}

So, when I render "TableList" I will also render "Table".

<TableList className="alunos-disponiveis">
  <tr>
    <th>Nome</th>
    <th>Endereço de Partida</th>
    <th>Endereço de Regresso</th>
  </tr>
  {
    data.passengerList.map(item => (
      <tr>
        <td>{item.name}</td>
        <td>{item.localeStart.address}</td>
        <td>{item.localeFinish.address}</td>
      </tr>
    ))
  }
</TableList>
    
14.04.2018 / 22:34