我无法访问另一个文件中的功能

时间:2019-08-26 08:44:53

标签: javascript node.js reactjs jsx

我想要一个输入,当输入某些内容时(onChange),该输入调用函数handleChangehandleChange在父文件中,因此我在父文件的组件中添加了一个道具handleChange={this.handleChange}

function InviteForm(props) {
  const [nbInvites, setNbInvites] = useState(1);
  const onAddInviteClick = e => {
    e.preventDefault();
    setNbInvites(nbInvites + 1);
  };
  console.log(nbInvites);
  let inviteList = [];
  for (var i = 0; i < nbInvites; i++) {
    inviteList.push(<InviteInput key={i} />);
  }
  return (
    <div>
      <form>{inviteList}</form>
      <AddInvitesButton onClick={onAddInviteClick} />
    </div>
  );
}

function InviteInput(props) {
  return (
    <li>
      <input
        className="form-input"
        type="email"
        placeholder="nom@exemple.com"
        name="invites"
        onChange={handleChange("invites")}
        required
      />
    </li>
  );
}
function Invites(props) {
  return (
    <div>
      <Title />
      <InviteForm />
    </div>
  );
}

父文件

        return (
          <Invites
            nextStep={this.nextStep}
            handleChange={this.handleChange}
            values={values}
          />
        );

错误是:第51行:'handleChange'未定义为no-undef

搜索关键字以详细了解每个错误。

- 谢谢您的帮助

2 个答案:

答案 0 :(得分:3)

您没有将道具传递给InputForm

function Invites(props) {
  return (
    <div>
      <Title />
      <InviteForm handleChange={props.handleChange}/> // Pass handleChange to the child component 
    </div>
  );
}

function InviteForm(props) {
  const [nbInvites, setNbInvites] = useState(1);
  const onAddInviteClick = e => {
    e.preventDefault();
    setNbInvites(nbInvites + 1);
  };
  console.log(nbInvites);
  let inviteList = [];
  for (var i = 0; i < nbInvites; i++) {
    inviteList.push(<InviteInput key={i} handleChange={props.handleChange}/>);  // Pass handleChange to the child component 
  }
  return (
    <div>
      <form>{inviteList}</form>
      <AddInvitesButton onClick={onAddInviteClick} />
    </div>
  );
}

function InviteInput(props) {
  return (
    <li>
      <input
        className="form-input"
        type="email"
        placeholder="nom@exemple.com"
        name="invites"
        onChange={props.handleChange("invites")} // Read it from the props
        required
      />
    </li>
  );
}

在这种情况下,由于您需要在多个级别上传递道具,因此通常建议您使用React Context apiRedux

答案 1 :(得分:0)

您已经将handleChange道具传递给了邀请列表组件。

 let inviteList = [];
  for (var i = 0; i < nbInvites; i++) {
    inviteList.push(<InviteInput key={i} handleChange={props.handleChange} />);
  }