Как поднять несколько значений в состоянии из отправки формы? - PullRequest
1 голос
/ 05 августа 2020

Моя цель - взять входное значение и значение радио-входа и поднять их состояние до родительского компонента App.js при отправке формы. Я использую два события onChange, и когда форма отправляется, значения поддерживаются и обрабатываются отдельными функциями в app. js. Проблема в том, что мне нужно передать два параметра значения функции handleNote. Я знаю, что я здесь на неправильном пути. Заранее спасибо.

import React, { Component } from "react";
import "./styles.css";
import Header from "./Header";

//app.js

class App extends Component {

  handleColor = (value) => {
    this.setState({
      noteColor: value
    });
  };

  handleNote = (value) => {
    this.setState({
      noteTitle: value
      // noteColor: value,
    });
  };

  render() {
    return (
      <div>
        <Header handleNote={this.handleNote} handleColor={this.handleColor} />
      </div>
    );
  }
}

export default App;
import React, { Component } from "react";
import "./styles.css";

//Header.js

class Header extends Component {
  constructor() {
    super();
    this.state = {
      note: "",
      noteColor: "white"
    };
  }

  handleSubmit = e => {
    e.preventDefault();

    // lifting state to handleNote()
    this.props.handleNote(this.state.note);

    // have this.state.noteColor lift within handleNote()
    this.props.handleColor(this.state.noteColor);

    this.setState({
      note: ""
    });
  };

  handleChange = e => {
    this.setState({
      note: e.target.value
      // noteColor should be here
    });
  };

  handleColor = e => {
    this.setState({
      noteColor: e.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="name" className="sr-only">
          Type anything that you need to know for later...
        </label>
        <input
          type="text"
          name="note"
          placeholder={this.state.placeholder}
          onChange={this.handleChange}
          value={this.state.note}
          required
        />
        <div className="radio-container">
          <label htmlFor="yellow" className="sr-only">
            White
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="white"
            id="white"
          />

          <label htmlFor="yellow" className="sr-only">
            Yellow
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="yellow"
            id="yellow"
          />

          <label htmlFor="yellow" className="sr-only">
            Red
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="red"
            id="red"
          />

          <label htmlFor="yellow" className="sr-only">
            Green
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="green"
            id="green"
          />

          <label htmlFor="yellow" className="sr-only">
            Blue
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="blue"
            id="blue"
          />

          <label htmlFor="yellow" className="sr-only">
            Purple
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="purple"
            id="purple"
          />
        </div>
      </form>
    );
  }
}

export default Header;

Ответы [ 3 ]

1 голос
/ 05 августа 2020

Вы немного усложняете это. Я бы упростил его примерно так:

Приложение. js

import React, { Component } from 'react';
import './styles.css';
import Header from './Header';

class App extends Component {
  handleNote = ({ note, noteColor }) => {
    console.log('note', note);
    console.log('notecolor', noteColor);
    this.setState({
      noteTitle: note,
      noteColor,
    });
  };

  render() {
    console.log('this.state', this.state);
    return (
      <div>
        <Header handleNote={this.handleNote} />
      </div>
    );
  }
}

export default App;

Заголовок. js

import React, { Component } from 'react';
import './styles.css';

class Header extends Component {
  constructor(props) {
    super(props);

    const initialState = {
      note: '',
      noteColor: 'white',
    }

    this.state = initialState;

    this.handleChange.bind(this);
  }

  handleChange = ({ target: { name, value } }) => {
    this.setState({
      [name]: value,
    });
  };

  render() {
    return (
      <form
        onSubmit={e => {
          e.preventDefault();
          this.props.handleNote(this.state);

          // reset local state
          this.setState(initialState);
        }}
      >
        <label htmlFor="name" className="sr-only">
          Type anything that you need to know for later...
        </label>
        <input
          type="text"
          name="note"
          placeholder={this.state.placeholder}
          onChange={this.handleChange}
          value={this.state.note}
          required
        />
        <div className="radio-container">
          <label htmlFor="yellow" className="sr-only">
            White
          </label>
          <input
            onChange={this.handleChange}
            type="radio"
            name="noteColor"
            value="white"
            id="white"
          />

          <label htmlFor="yellow" className="sr-only">
            Yellow
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="yellow"
            id="yellow"
          />

          <label htmlFor="yellow" className="sr-only">
            Red
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="red"
            id="red"
          />

          <label htmlFor="yellow" className="sr-only">
            Green
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="green"
            id="green"
          />

          <label htmlFor="yellow" className="sr-only">
            Blue
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="blue"
            id="blue"
          />

          <label htmlFor="yellow" className="sr-only">
            Purple
          </label>
          <input
            onChange={this.handleColor}
            type="radio"
            name="color"
            value="purple"
            id="purple"
          />
        </div>
      </form>
    );
  }
}

export default Header;
0 голосов
/ 05 августа 2020
import React, { Component } from "react";
import "./styles.css";
import Header from "./Header";

//app.js

class App extends Component {


  handleNote = (title,color) => {
    this.setState({
      noteTitle: title
      noteColor: color,
    });
  };

  render() {
    return (
      <div>
        <Header handleNote={this.handleNote} />
      </div>
    );
  }
}

export default App;

import React, { Component } from "react";
import "./styles.css";

//Header.js

class Header extends Component {
  constructor() {
    super();
    this.state = {
      note: "",
      noteColor: "white"
    };
  }

  handleSubmit = e => {
    e.preventDefault();

    // lifting state to handleNote()
    this.props.handleNote(this.state.note,this.state.noteColor);
    this.setState({
      note: ""
    });
  };


  handleChange = (name,e) => {
    this.setState({
      [name]: e.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="name" className="sr-only">
          Type anything that you need to know for later...
        </label>
        <input
          type="text"
          name="note"
          placeholder={this.state.placeholder}
          onChange={(e)=>this.handleChange("note",e)}
          value={this.state.note}
          required
        />
        <div className="radio-container">
          <label htmlFor="yellow" className="sr-only">
            White
          </label>
          <input
            onChange={(e)=>this.handleChange("noteColor",e)}
            type="radio"
            name="color"
            value="white"
            id="white"
          />

          <label htmlFor="yellow" className="sr-only">
            Yellow
          </label>
          <input
            onChange={(e)=>this.handleChange("noteColor",e)}
            type="radio"
            name="color"
            value="yellow"
            id="yellow"
          />

          <label htmlFor="yellow" className="sr-only">
            Red
          </label>
          <input
            onChange={(e)=>this.handleChange("noteColor",e)}
            type="radio"
            name="color"
            value="red"
            id="red"
          />

          <label htmlFor="yellow" className="sr-only">
            Green
          </label>
          <input
            onChange={(e)=>this.handleChange("noteColor",e)}
            type="radio"
            name="color"
            value="green"
            id="green"
          />

          <label htmlFor="yellow" className="sr-only">
            Blue
          </label>
          <input
            onChange={(e)=>this.handleChange("noteColor",e)}
            type="radio"
            name="color"
            value="blue"
            id="blue"
          />

          <label htmlFor="yellow" className="sr-only">
            Purple
          </label>
          <input
            onChange={(e)=>this.handleChange("noteColor",e)}
            type="radio"
            name="color"
            value="purple"
            id="purple"
          />
        </div>
      </form>
    );
  }
}

export default Header;
0 голосов
/ 05 августа 2020

В настоящее время ваша функция handleSubmit создана и назначена для onSubmit в форме, но ничего не запускает функцию. Добавьте <button type="submit">Click me</button> в форму для запуска handleSubmit.

...