处理程序在React中的子组件中没有按预期工作

时间:2017-12-02 19:39:58

标签: javascript reactjs react-props

我是学校考试部分的最后一个规格。

  
    

select应该有一个提交新动物的onChange事件

  

基本上我似乎无法将handleSubmit函数传递给孩子,以响应变化...... 这是规范的其余部分。

it('select should have an onChange event that submits the new animal', () => {
  expect(animalSelect.props('select').onChange).to.be.function;

  // choosing a random animal
  let animal = getRandomAnimal();

   // simulating a 'change' event with an event described as the second argument given to `simulate`
   animalSelect.find('select').simulate('change', { target: { value: animal } });

   // the spy sent in should be called with the argument described
   expect(setAnimalSpy.calledWith(animal)).to.be.true;
 });

这是父组件Exhibit

import React, { Component } from 'react';
import AnimalSelect from './AnimalSelect';
import Cage from './Cage';

export default class Exhibit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedAnimal: this.props.selectedAnimal,
    };
    this.setAnimal = this.setAnimal.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  setAnimal(animal) {
    this.setState({ selectedAnimal: animal });
  }

  handleSubmit(event) {
    this.setState({ selectedAnimal: event.target.value });
  }

  render() {
    const { selectedAnimal } = this.state;
    return (
      <div className="exhibit">
        <AnimalSelect handleSubmit={this.handleSubmit} submitAnimal={this.setAnimal} animals={this.props.animals} />
        <Cage selectedAnimal={selectedAnimal} />
      </div>
    );
  }
}

这是AnimalSelectExhibit)组件的成员:

import React, { Component } from 'react';

// exporting the constructor function (dumb component).
// what is the parameter coming in here?
export default function AnimalSelect(props) {
  // prettier-ignore
  return (
    <form>
      <label>Select an Animal: </label>
      <select onChange={() => props.handleSubmit}>
        {props.animals.map((animal, index) => {
          return (
            <option key={animal} value={animal}>
              {animal}
            </option>
          );
        })}
      </select>;
    </form>
  );
}

不幸的是,这是我遇到的唯一错误。

    AssertionError: expected false to be true

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在这里,您将事件处理程序设置为匿名函数,该函数返回对函数的引用:

<select onChange={() => props.handleSubmit}>

你可能想要更像这样的东西:

<select onChange={evt => props.handleSubmit(evt)}>

这有效地将事件处理程序委托给父组件的函数,并将事件对象传递给它。虽然我不确定为什么按照评论中的建议设置处理程序并不起作用。