反应:TypeError:无法读取未定义的属性“值”

时间:2019-02-28 12:23:00

标签: javascript reactjs ecmascript-6

我从ReactJS的表单中获得价值,但与此同时,当我单击“提交”按钮时,它给了我错误TypeError: Cannot read property 'value' of undefined。有人可以检查我可能遇到的问题。

谢谢

import React, { Component } from 'react'
import { getFunName } from './helpers';

class StorePicker extends Component {
  myInput=React.createRef();

  goToStore=event=> {
    // 1- Stopping form from submitting
    event.preventDefault();

    // 2 - Getting value from Input
    const storeName = this.myInput.value.value ;

    // 3 - Change the page to /store/whatever-you-entered
    this.props.history.push(`/store/${storeName}`)
  }


  render() {
    return (
     <form className="store-selector" onSubmit={this.goToStore}>
     <h2>Please Enter Enter a Store</h2>
     <input type="text" required placeholder="Store Name" ref={this.myInput}  defaultValue={getFunName()}/>
     <button type="submit">Visit Store</button>
     </form>
    )
  }
}

export default StorePicker;

2 个答案:

答案 0 :(得分:1)

如果您使用裁判,应该是这样:

const storeName = this.myInput.current.value;

答案 1 :(得分:0)

完整的代码

import React, {Fragment} from 'react';
import {getFunName} from "../helpers";

class StorePicker extends React.Component{

myInput = React.createRef();

goToStore = event =>{
    //1. Stop the from submitting
     event.preventDefault();

     //2. get the text from that input
     const storeName = this.myInput.current.value;

     //3. change the page to /store/store-name
     this.props.history.push(`/store/${storeName}`);
}

render(){
    return(
        <form className="store-selector" onSubmit={this.goToStore}>
            <h2>Please Enter a Store</h2>
            <input type="text" ref={this.myInput} required placeholder="Store Name"/>
            <button type="submit">Visit Store</button>
        </form>
    )
}
}

export default StorePicker;