Controlled Input Stateless Aggregates

Currently, to control the controlled inputs inside Stateless React components, I wrap a stateless component inside a fully functional Sate component.

For instance,

const InputComponent = (props) => {
  return (
    <input value={props.name} onChange={props.handleChange} />
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Tekeste'
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({
      name: event.target.value
    });
  }
  render() {
    return (
      <InputComponent name={this.state.name} handleChange={this.handleChange} />
    );
  }
}

What I would like to know are a few things.

  • Is this a good sample?
  • If not, how can I achieve my goal, that is, have controlled inputs inside stateless components.
+4
source share
2 answers

InputComponent , , . , , ES7 :

class App extends React.Component {
  state = {
    name: 'Tekeste'
  };

  handleChange = (event) => {
    this.setState({
      name: event.target.value
    });
  }

  render() {
    return (
      <InputComponent name={this.state.name} handleChange={this.handleChange} />
    );
  }
}

create-react-app, .

, value onChange, .

+3

@frontsideair, - , https://github.com/NullVoxPopuli/react-state-helpers

import React, { Component } from 'react';
import stateWrapper from 'react-state-helpers';

class App extends Component {
  render() {
    const { 
      mut, 
      values: { name } 
    } = this.props;

    return <InputComponent name={name} handleChange={mut('name')} />;
  }
}

export default stateWrapper(App)
0

Source: https://habr.com/ru/post/1678956/


All Articles