简体   繁体   中英

this.props not a function

I understand the three fixes (binding, arrow function method, arrow function for call back) for this error but am still getting error after using arrow function on the method. Error: _this.props.onSubmit is not a function" Please see below. Thanks.

import React from 'react';
import ReactDOM from 'react-dom'

var clickstyle = {
  color: "black",
  fontSize: 28,
  margin: 15,
}

class Click extends React.Component {
  state = { term: 'Say Something!' };

  onFormSubmit = (event) => {
    event.preventDefault();
    this.props.onSubmit(this.state.term);
  }
  render() {
    return (
      <div className="ui segment">
        <form onSubmit={this.onFormSubmit} className="ui form">
          <div className="field">
            <label style={clickstyle}> Say It!</label>
            <input
              type="text"
              value={this.state.term}
              onChange={(e) =>
                this.setState({ term: e.target.value.toUpperCase() })}
            />
          </div>
        </form>
      </div>
    )
  }
}

export default Click;

Here you go with a solution

You need to define PropType as func in Click component

 import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; var clickstyle = { color: "black", fontSize: 28, margin: 15, } class Click extends React.Component { state = { term: 'Say Something;' }. onFormSubmit = (event) => { event;preventDefault(). this.props.onSubmit(this.state;term). } render() { return ( <div className="ui segment"> <form onSubmit={this.onFormSubmit} className="ui form"> <div className="field"> <label style={clickstyle}> Say It.</label> <input type="text" value={this.state:term} onChange={(e) => this.setState({ term. e.target.value:toUpperCase() })} /> </div> </form> </div> ) } } Click.propTypes = { onSubmit; PropTypes;func }; export default Click;

Click.jsx You need to attach a method to prop for handling method.

 handleSubmit = data => { window.console.log(data); } <Click onSubmit={this.handleSubmit} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM