访问子组件的值

时间:2018-07-01 09:39:42

标签: reactjs input web-applications login onchange

我想从父组件访问子输入组件的值。我遵循了这个问题的答案:How to access child's state in React? ,但是它不起作用。输入文本时,输入字段不会更新,并且出现此错误:

Uncaught TypeError: Cannot read property 'setState' of undefined
        at onFieldsChange (bundle.js:28511)
        at HTMLUnknownElement.callCallback (bundle.js:2807)
        at Object.invokeGuardedCallbackDev (bundle.js:2845)
        at Object.invokeGuardedCallback (bundle.js:2894)
        at Object.invokeGuardedCallbackAndCatchFirstError (bundle.js:2908)
        at executeDispatch (bundle.js:3173)
        at executeDispatchesInOrder (bundle.js:3195)
        at executeDispatchesAndRelease (bundle.js:3293)
        at executeDispatchesAndReleaseTopLevel (bundle.js:3304)
        at Array.forEach (<anonymous>)

更新:我通过对onFieldsChange中的LoginForm使用箭头功能来修复了控制台错误,但是当我键入文本时,这些字段仍然没有更新。

这是我的LoginForm,它是父组件:

import React, { Component } from 'react';
import Button from '../Recyclable/Button';
import AlertBar from '../Recyclable/AlertBar';
import InputGroup from '../Recyclable/InputGroup';
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux';

export default class LoginForm extends Component {
    constructor (props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            rememberMe: false,
            submitting: false
        };
    }

    onChangeCheckBox = (event) => {
        this.setState({  [event.target.name]: event.target.checked });
    };

    validateLoginForm = (username,password) => {
        if(username.length >= 0 && password.length >= 0){
            return true;
        }
        this.props.loginError = {
            message: 'All fields are required'
        }
        return false;       
    }

    onSubmit = (event) =>  {
        event.preventDefault();
        console.log('submitted');
        let { username, password } = this.state;
        console.log(username, password);
        if(this.validateLoginForm(username,password)) {
            this.props.login(username, password);
        }
        this.setState({
            username: '',
            password: ''
        });
    }

    onFieldsChange = (fieldId, value) => {
        console.log([fieldId]);
        this.setState({ [fieldId]: value });
    }

    render() {
        const { loginError } = this.props;
        return (
            <div className="container">
                <div className="login-container">
                    <div id="output">{loginError}</div>
                    <div className="avatar"></div>
                    <h3>Login</h3>
                    <div className="form-box">
                        <form onSubmit={this.onSubmit} >
                            <InputGroup 
                                name="username" 
                                type="text" 
                                placeholder="username" 
                                onChange={this.onFieldsChange}
                                value={this.state['username']}
                            />
                            <InputGroup 
                                name="password" 
                                type="password" 
                                placeholder="password" 
                                onChange={this.onFieldsChange} 
                                value={this.state['password']} 
                            />
                            <div className="small-text"></div>
                            <div className="small-text" >
                                <a href="#">Forgot password?</a>
                            </div>
                            <Button buttonLabel="Login" />
                        </form>

                    </div>
                </div>
            </div>
        );
    }
}

这是我的InputGroup,它是子组件:

import React, {Component} from 'react';

export default class InputGroup extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    const text = event.target.value;
    console.log('props name', this.props.name);
    this.props.onChange(this.props.name, text);
  }

  render() {
    return (
      <div className="input-group">
        <input onChange={this.handleChange} value={this.props.value} {...this.props} />
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

lexical scope问题。用户arrow function

 onFieldsChange=(fieldId, value) =>{
            console.log([fieldId]);
            this.setState({ [fieldId]: value });
        }

check here以获取更多信息。