无法读取null的属性'value'?

时间:2017-06-14 13:36:24

标签: reactjs react-redux

我尝试使用this.username.value时遇到错误。我希望获得文本框的值以在标签中显示。我是新手做出反应。如何从Textbox获取值到变量并使用InputRef在Label中显示。

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { createStructuredSelector } from 'reselect';
import TextBox from 'components/Atoms/TextBox';
import makeSelectTestPage from './selectors';

export class TestPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.username ='',
    this.handelChange = this.handelChange.bind(this);
  }
  handelChange() {
    console.log("Log",this.username.value);
    <label> this.username.value</label>
  }
  render() {
    return (
      <div>
        <Helmet
          title="TestPage"
          meta={[
            { name: 'description', content: 'Description of TestPage' },
          ]}
        />
        <TextBox labelName="Input Vaue" placeholder="Test" ref={(inputRef) => { this.username = inputRef; }} defaultValue="Text" ></TextBox>
        <button onClick={this.handelChange}>Login</button>
      </div>
    );
  }
}

TestPage.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  TestPage: makeSelectTestPage(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(TestPage);

1 个答案:

答案 0 :(得分:1)

在你的问题中有一些错误。尝试理解下一个代码,您将能够将它应用于您的示例:

class Test extends React.Component {
   
  constructor(props){
    super(props);
    this.state = {  
      value: "",
      username: ""
    }
  }

  handleChange(e){
    this.setState({value: e.target.value})
  }

  handleClick(){
    this.setState({username: this.state.value})
  }

  render(){
    return (
      <div>
        <label>{this.state.username}</label><br />
        <input value={this.state.value} onChange={this.handleChange.bind(this)}></input><br />
        <button onClick={this.handleClick.bind(this)}>Login</button>
      </div>
    )
  }
}

ReactDOM.render(<Test />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>

Here is the fiddle.