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

How can get Value from child component in react?

我创建了一个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;

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

在 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

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

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

将道具传递给子组件:

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

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

this.props.onChange(event.target.value)