我在提交数据到我的表时遇到了麻烦

时间:2019-08-17 08:02:40

标签: reactjs

我是React的新手,它试图弄清楚如何在Submit表中输入信息。我尝试按照教程进行操作,但是当您是新手时,很难知道您的关注内容。我希望实现的输出是在文本框中输入锻炼内容,选择进行锻炼的日期,然后按提交按钮,锻炼将填充与所选日期匹配的表格

我很欣赏我的代码可能不是很好。但是,这里的任何帮助都会很棒。

import './App.css';
import 'bootstrap/dist/css/bootstrap.css';
import Header from './components/Header';
import WorkOutList from './components/WorkoutList';
//import WorkoutAdder from './components/WorkoutAdder';
import WeightAdder from './components/WeightAdder';


function App() {
  return (
    <div className="App">
      <Header />
      <WorkOutList />
      <WeightAdder />
    </div>
  );
}

export default App;

import React from 'react';

class WorkoutAdder extends React.Component {
  state = {
    workout: '',
    day: ''
  };

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

  render() {
    console.log(this.state);
    return (
      <div>
        <p>Todays Workout is:{this.props.dayMatcher[0].exercise}</p>
        <form onSubmit={this.props.handleSubmit}>
          <h4>Select a day to add workout </h4>
          <label htmlFor="day" id="day" />
          <select
            className="btn btn-primary dropdown-toggle"
            type="text"
            name="day"
            onChange={this.handleInputChange}
          >
            <option value="n/a">pick a day</option>
            <option value="Mon"> Mon</option>
            <option value="Tue"> Tue</option>
            <option value="Wed"> Wed</option>
            <option value="Thu"> Thu</option>
            <option value="Fri"> Fri</option>
            <option value="Sat"> Sat</option>
          </select>
          <br />
          <br />
          <input
            type="text"
            placeholder="Enter Workout Here"
            name="workout"
            onChange={this.handleInputChange}
          />
        </form>
        <br />
        <p>
          <button
            onClick={this.handleSubmit}
            className="btn btn-primary btn-sm"
          >
            {' '}
            Add Workout
          </button>
        </p>
      </div>
    );
  }
}

export default WorkoutAdder;

import React from 'react';
import WorkoutAdder from './WorkoutAdder';

class WorkOutList extends React.Component {
  state = {
    workout: [
      { exercise: '', day: 'Mon', weight: 0, dayNum: 1 },
      { exercise: '', day: 'Tue', weight: 0, dayNum: 2 },
      { exercise: '', day: 'Wed', weight: 0, dayNum: 3 },
      { exercise: '', day: 'Thu', weight: 0, dayNum: 4 },
      { exercise: 'Yoga', day: 'Fri', weight: 0, dayNum: 5 },
      { exercise: '', day: 'Sat', weight: 0, dayNum: 6 }
    ]
  };


  handleSubmit = event => {
    event.preventDefault();
    this.setState(currentState => {
      let copyArr = [...currentState.workout];
      let newArr = copyArr.map(copy => {
        const copyWorkout = copy;
        copyWorkout.exercise = copyArr.push(this.props.handleInputChange);
        console.log(copyWorkout);
        return copyWorkout;
      });
      console.log(newArr);
      this.setState({ newArr });
    });
  };

  render() {
    const getToday = new Date().getDay();

    const dayMatcher = this.state.workout.filter(d => {
      if (d.dayNum === getToday) {
        return d.day;
      }
      return this.dayMatcher;
    });
    // console.log(new Date());
    // const theDate = new Date();
    // console.log(theDate.getDay());
    return (
      <>
        <WorkoutAdder
          dayMatcher={dayMatcher}
          handleSubmit={this.handleSubmit}
        />

        <div className="grid-container">
          {this.state.workout.map(exercise => {
            return (
              <div className="grid-item" key={exercise.day}>
                {exercise.day}-{exercise.exercise}
              </div>
            );
          })}
        </div>
      </>
    );
  }
}

export default WorkOutList;

2 个答案:

答案 0 :(得分:1)

第一个问题是您需要在 WorkoutAdder 组件中传递handleSubmit不是您的类函数,即您需要像这样修复:

<button
            onClick={this.props.handleSubmit} //need to add like this
            className="btn btn-primary btn-sm"
          >
            {' '}
            Add Workout
          </button>

另一个问题是您没有在 handleSubmit函数中正确设置状态。您无需执行nestedSetState。

this.setState({ newArr });

它用newArr变量设置newArr状态的作用是什么。就您而言,应该是锻炼。

handleSubmitCode应该像这样:

handleSubmit = (event,data) => {
    event.preventDefault();
    console.log("Data",data);
    let copyArr = [...this.state.workout];
      let updateData = copyArr.map(stateData => { //check if it meets current one then update the excercise
        if(stateData.day===data.day){
          return {...stateData,exercise:data.workout,}
        }
        else{
          return stateData;
        }
      });
      this.setState({ workout:updateData }); //Update with new state
  };

内部 WorkoutAdder 组件

<button
            onClick={(e) => this.props.handleSubmit(e,this.state)}
            className="btn btn-primary btn-sm"
          >
            {' '}
            Add Workout
          </button>

演示:

Edit wizardly-hoover-u3lb6

答案 1 :(得分:0)

好吧,因为您在父组件class Board(): DIMENSIONS = [8, 8] #board and pieces have their respective rules. def __init__(self, D=[8,8]): if len(D) <= 0: board = [None for i in range(D)] else: board = [None for i in range(D[0])] for j in range(1,len(D)): board = [board for i in range(D[j])] def get(self, location): try: for coordinate in location: result = board[coordinate] return result except: print('Error: Cannot get coordinate') return None def set(self, location, piece): try: for coordinate in location: result = self.board[coordinate] result = piece except: print('Error: Cannot set coordinate') def move(self, start, end): x = self.get(start) if x is not None: for m, r in x.moves, x.rules: if self.get(is_legitimate(self, start, m, r)) == end: = x pass #Check alignment and position, if it's transformable react according to board rules. #returns false if not, but returns location if legit. def is_legitimate(self, start, move, rule): location = start forwardback = True while move != 1: primes = [2] while move % primes[-1] == 0: if forwardback: location[len(primes) // 2]+=1 else: location[len(primes) // 2]-=1 move = move % primes[-1] if not self.bounds(location): return False primes.append(next_prime(primes)) forwardback = not forwardback def bounds(self, location): for coordinate, d in location, self.DIMENSIONS: if coordinate < 0 or coordinate > d: return False return True #using prime numbers? def next_prime(primes): if len(primes) == 0: return 2 prev_result = 1 result = 2 while prev_result != result: prev_result = result for x in primes: if result == x or result % x == 0: result += 1 break return result 中将函数WorkOutList发送到子组件handleSubmit。您可以从属性而不是组件实例本身访问它。所以:

WorkoutAdder

应该是

      <button
        onClick={this.handleSubmit}
        className="btn btn-primary btn-sm"
      >
        {' '}
        Add Workout
      </button>