【问题标题】:How can get Value from child component in react?如何从子组件中获取价值?
【发布时间】:2019-05-13 12:15:40
【问题描述】:

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

【问题讨论】:

    标签: reactjs forms input components submit


    【解决方案1】:

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

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

    将 props 传递给子组件:

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

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

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

    【讨论】:

      【解决方案2】:

      在 React 中,数据以一种方式从父级流向子级。

      因此,您需要在FormComponent 处拥有输入的实际状态,并将它们作为道具传递给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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 我不明白,你能给我解释一下吗?
        猜你喜欢
        • 2020-08-11
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多