如何从子组件中获取价值?

时间:2018-12-12 11:38:17

标签: reactjs forms input components submit

我创建了一个InputComponent,我想将此组件导入其他组件并进行提交,但是我不能这样做。如何从FormComponent的子组件中获取价值

InputComponent.js

import React, {Component} from 'react';

class InputComponent extends Component {
    constructor(props) {
        super(props);
        this.state = { currentVal: null }
    }

    render() { 
        return ( 
            <div>
                <input  
                    value={this.state.currentVal}
                    onChange={(event) => this.setState({currentVal:event.target.value })}
                   /> 
            </div>
         );
    }
}

export default InputComponent;

FormComponent.js

import React,{Component} from 'react';
import InputComponent from '../../components/common/InputComponent';

class FormComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }


    CallSubmit= (event) => {  
        // how can get username and password ?

        event.preventDefault();
        console.log(event.target.vale)

    }

    render() { 
        return ( 

            <div style={{width:100, height:500, marginTop:100}}>
                <form onSubmit={  this.CallSubmit }>
                    <InputComponent name="username" />
                    <InputComponent name="password" />

                    <button>Send it</button>
                </form>
            </div>
         );
    }
}

export default FormComponent;

3 个答案:

答案 0 :(得分:1)

在父组件中移动onChange函数,并将用户名和密码存储在FormComponent组件中

答案 1 :(得分:1)

您可以在子组件上创建onChange操作,例如,这是您的FormComponent: 创建此函数来处理更改:

val yourMap = formules.splitToSequence("<br />")
    .filter { it.contains("=") }
    .map { it.split("""\s*=\s*""".toRegex(), limit = 2) }
    .map { (key, value) -> key to value } // destructuring
    .toMap()

// or: instead of filtering do a takeif and if you require those keys, do something appropriate there (e.g. set a default value instead)
val yourMap = formules.splitToSequence("<br />")
    .map { it.split("""\s*=\s*""".toRegex(), limit = 2) }
    .mapNotNull { it.takeIf { it.size == 2 } } // this discards now the entries without any value
    .map { (key, value) -> key to value } // destructuring
    .toMap()

将道具传递给子组件:

onChangeUsername(username){
 this.setState({username})
 }

在子组件(InputComponent)中,您可以访问此道具并将数据传递给它:

<InputComponent name="username" onChange = {this.onChangeUsername} />

答案 2 :(得分:0)

在React中,数据从父级流到子级一种方式

因此,您需要在FormComponent处具有输入的实际状态,并将其作为props传递给InputComponent,并在FormComponent处处理输入的实际状态。

<div>
  <InputComponent 
    input={this.state.username} 
    onChange={this.handleInputChange}
  />
  <InputComponent 
    input={this.state.password} 
    onChange={this.handleInputChange}
  />
</div>

一篇不错的文章:https://openclassrooms.com/en/courses/4286486-build-web-apps-with-reactjs/4286721-understand-one-way-data-bindings