简体   繁体   English

为什么这个孙子的论点没有定义? (上下文,反应)

[英]Why is this grandchild's argument not defined? (Context, React)

TL;DR I'm trying to send arguments from a grandchild component to App.js using Context. TL;DR 我正在尝试使用上下文将参数从孙组件发送到 App.js。 It's being called, but its arguments are undefined.它正在被调用,但它的参数是未定义的。

Here is what I return in App.js render():这是我在 App.js render() 中返回的内容:

.... 
setId(data){
    alert('called')
    console.log(data)
}
render(){
    return
    (<UserContext.Provider value = {{setId: this.setId.bind(this)}}>
      <StartPage/>
    </UserContext.Provider>)

}

Startpage contains a component called LoginForm, which I want to call setId from. Startpage 包含一个名为 LoginForm 的组件,我想从中调用 setId。 In LoginForm:在登录表单中:

    login(context, e){
        e.preventDefault
        context.setId('test')
    }

    render(){
        return(
            <UserContext.Consumer>
            {(context)=>{
            return(
                <form onSubmit = {this.login.bind(this, context)}>
                 .....
                </form>)}
            <UserContext.Consumer>
    }

When I submit from LoginForm, I do get an alert, but my console.log logs 'undefined'.当我从 LoginForm 提交时,我确实收到了警报,但我的 console.log 记录了“未定义”。 It seems like I'm passing and using the correct function (setId) from App.js, but I'm not correctly passing back an argument from LoginForm...似乎我正在从 App.js 传递和使用正确的函数 (setId),但我没有正确地从 LoginForm 传回参数...

The sample code you provide has some error, should fail to execute.您提供的示例代码有一些错误,应该无法执行。 Maybe due to you just copy/paste part of your original code.也许是因为您只是复制/粘贴了原始代码的一部分。 But after I fix all the errors, it works as expected.但是在我修复所有错误后,它按预期工作。 Here is the updated version.这是更新的版本。

import React, { Component } from "react";

const UserContext = React.createContext({});

class StartPage extends Component {
  login(context, e) {
    e.preventDefault();
    context.setId("test");
  }

  render() {
    return (
      <UserContext.Consumer>
        {context => (
          <form onSubmit={this.login.bind(this, context)}>
            <input type="text" value="some value" onChange={console.log} />
            <button type="submit">SUBMIT</button>
          </form>
        )}
      </UserContext.Consumer>
    );
  }
}

export default class ContextForm extends Component {
  setId(data) {
    console.log("called", data);
  }

  render() {
    return (
      <UserContext.Provider value={{ setId: this.setId.bind(this) }}>
        <StartPage />
      </UserContext.Provider>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM