React - 子组件可以将值发送回父表单

时间:2017-01-12 17:13:51

标签: javascript forms reactjs input components

InputField& Button是用于创建表单的表单的自定义组件。我的问题是如何将数据发送回表单,以便在单击按钮时,我可以使用数据(用户名和密码)在表单上激活ajax:

export default auth.authApi(
  class SignUpViaEmail extends Component{

    constructor(props){
      super(props);
      this.state = {
        email : "",
        password : ""
      };
      this.storeEmail = this.storeEmail.bind( this );
      this.storePassword = this.storePassword.bind( this );
    }

    storeEmail(e){
      this.setState({ email : e.target.value });
    }

    storePassword(e){
      this.setState({ password : e.target.value });
    }

    handleSignUp(){
      this.props.handleSignUp(this.state);
    }

    render(){
      return(
        <div className="pageContainer">

          <form action="" method="post">
            <InputField labelClass = "label"
                        labelText = "Username"
                        inputId = "signUp_username"
                        inputType = "email"
                        inputPlaceholder = "registered email"
                        inputClass = "input" />
            <Button btnClass = "btnClass"
                    btnLabel = "Submit"
                    onClickEvent = { handleSignUp } />
          </form>
        </div>
      );
    }

  }
);

或不推荐&amp;我不应该在表单中创建自定义子组件?

子组件=&gt; InputField

import React,
       { Component } from "react";

export class InputField extends Component{

  constructor( props ){
    super( props );
    this.state = {
      value : ""
    };
    this.onUserInput = this.onUserInput.bind( this );
  }

  onUserInput( e ){
    this.setState({ value : e.target.value });
    this.props.storeInParentState({[ this.props.inputType ] : e.target.value });
  }

  render(){
    return  <div className = "">
              <label htmlFor = {this.props.inputId}
                     className = {this.props.labelClass}>
                {this.props.labelText}
              </label>
              <input id = {this.props.inputId}
                     type = {this.props.inputType}
                     onChange = {this.onUserInput} />
              <span className = {this.props.validationClass}>
                { this.props.validationNotice }
              </span>
            </div>;
  }
}

错误:我在父storeEmail func上收到错误e.target is undefined

3 个答案:

答案 0 :(得分:33)

React的单向数据绑定模型意味着子组件无法将值发送回父组件,除非明确允许这样做。 React的做法是将回调传递给子组件(参见Facebook's "Forms" guide)。

class Parent extends Component {
  constructor() {
    this.state = {
      value: ''
    };
  }

  //...

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

  //...

  render() {
    return (
      <Child
        value={this.state.value}
        onChangeValue={this.handleChangeValue}
      />
    );
  }
}

class Child extends Component {
  //...

  render() {
    return (
      <input
        type="text"
        value={this.props.value}
        onChange={this.props.onChangeValue}
      />
    );
  }
}

请注意,父组件处理状态,而子组件仅处理显示Facebook's "Lifting State Up" guide是学习如何做到这一点的好资源。

这样,所有数据都存在于父组件中(处于状态),子组件只有一种方式来更新该数据(作为道具传递的回调)。现在您的问题得到了解决:您的父组件可以访问它所需的所有数据(因为数据存储在状态中),但您的子组件负责将数据绑定到它们各自的元素,例如{{1} }标签。

答案 1 :(得分:2)

父母

import React, { Component } from 'react';
import Child from './child'
class Parent extends Component {
  state = {
    value: ''
  }
  onChangeValueHandler = (val) => {
    this.setState({ value: val.target.value })
  }
  render() {
    const { value } = this.state;
    return (
      <div>
        <p> the value is : {value} </p>
        <Child value={value} onChangeValue={this.onChangeValueHandler} />
      </div>
    );
  }
}

export default Parent;

孩子

  import React, { Component } from 'react';
  class Child extends Component {
  render() {
  const { value , onChangeValue } = this.props;
  return (
    <div>
      <input type="text"  value={value} onChange={onChangeValue}/> 
    </div>
  );
}
}
  export default Child;

您可以在https://codesandbox.io/s/two-way-binding-qq1o1?from-embed

上看到实时示例。

答案 2 :(得分:-6)

您可以添加&#34;参考名称&#34;在你的InputField中,你可以从中调用一些函数,如:

<InputField 
   ref="userInput"
   labelClass = "label"
   labelText = "Username"
   inputId = "signUp_username"
   inputType = "email"
   inputPlaceholder = "registered email"
   inputClass = "input" />

所以你可以使用refs访问它:

this.refs.userInput.getUsernamePassword();

其中getUsernamePassword函数将在InputField组件中,并且返回时您可以设置状态并调用props.handleSignUp

相关问题