猿问

类型错误:无法读取未定义的属性“telephoneno”

我正在 React JS 上尝试一个简单的程序,代码如下


class Employee extends Component {


    constructor() {


        super();


        this.state = {

            name: '',

            address: '',

            city: '',

            telephoneno: '',

            stdcode: ''

                        

        }


        // Other event handlers goes here

        this.handlePhoneNoChange = this.handlePhoneNoChange(this);

    }


    handlePhoneNoChange(event) { 

        this.setState({ telephoneno: event.target.telephoneno });

    }


    render() {

        return (

            <center>

                <div>


                    <div class="input-group input-group-sm w-50">

                        <div class="input-group-prepend">

                            <span class="input-group-text" id="basic-addon1">Phone No</span>

                        </div>

                            

                            <input type="text" class="form-control" placeholder="Phone No" id="phoneno" aria-label="PhoneNo" aria-describedby="basic-addon1" onChange={ this.handlePhoneNoChange } value={ this.state.telephoneno } /><br/>

                    </div><br/>

           

                 </div>  

            </center>

        );

    }

}

 

export default Employee;

它与'TypeError: Cannot read property 'telephoneno'未定义的错误。


我试图在这里理解这个概念。


为什么它只报告“telephoneno”错误而不报告其他字段?我究竟做错了什么 ?


婷婷同学_
浏览 168回答 3
3回答

红糖糍粑

问题是这一行:this.handlePhoneNoChange = this.handlePhoneNoChange(this);如果你仔细观察,你就不见了.bind。因此,您将其称为this事件。您的组件中没有target属性,因此会引发错误。错误的修复是:this.handlePhoneNoChange = this.handlePhoneNoChange.bind(this);但是,它不会解决其他答案中突出显示的问题。

慕田峪4524236

event.target.value基本上检索调用它的任何输入的值。在这种情况下,可以通过 event.target.value 访问telephoneno输入的值所以,使用事件的正确方法是,handlePhoneNoChange(event) {&nbsp;&nbsp; &nbsp;this.setState({ telephoneno: event.target.value });}你应该像这样绑定它,this.handlePhoneNoChange = this.handlePhoneNoChange.bind(this);如果您可以在输入的 onChange 事件中使用箭头函数,那就更好了,onChange={ (e) => this.handlePhoneNoChange(e) }

扬帆大鱼

您没有使用正确的方式在反应有状态组件中使用状态,在和函数props中用作参数constructorsuper  constructor(props) {        super(props);        this.state = {            name: '',            address: '',            city: '',            telephoneno: '',            stdcode: ''                                }  }并更新这一行:this.setState({ telephoneno: event.target.value});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答