简体   繁体   中英

Need help to make a event handler to work properly in react js

I need to make this logic to be executed every time when input field value is changed:

  let warningMessage = ''

  if (stateData) {
    let list = []
    if (props.values.injured_worker_type === 'Seasonal') {
      list = stateData.calculation_warnings['Seasonal']
    } else {
      list = stateData.calculation_warnings[`FullTime-${props.values.working_days}`]
    }

    const keys = _.keys(list)
    const index = _.findIndex(keys, key => {
      const fromValue = Number(key.slice(1, key.indexOf('-')))
      const toValue = Number(key.slice(key.indexOf('-') + 1, key.length))
      return props.values.total_days_paid >= fromValue && props.values.total_days_paid < toValue
    })

    if (index >= 0) {
      warningMessage = list[keys[index]]
    }
  }

  const message = warningMessage ? (
    <p style={{ color: 'red', fontSize: '0.85rem' }}> {warningMessage} </p>
  ) : null

And pass downthis messeage to be outputed as result of this logic:

  const message = warningMessage ? (
   <p style={{ color: 'red', fontSize: '0.85rem' }}> {warningMessage} </p>
  ) : null

Here is JSX(html) part when I have that input field:

 return (
<Fragment>
  <Form.Group grouped style={{ marginTop: '2rem' }}>
    <label style={{ fontSize: '0.85rem' }}>8. Total days in preceeding 52 weeks:</label>
    <Form.Input
      name="total_days_paid"
      onChange={this.handleChange}
      width="6"
      placeholder="200"
      required
    />
  </Form.Group>

 {/* THIS messeage is result of that logic which I need to 
     be executed every time on changed input */}
      {message}
    </Fragment>

) }

Here is not working version of code in stackblitz: https://stackblitz.com/edit/react-tpk1ik

How I can make this to works?

The code in your example doesn't help much because it has errors and even when I install the missing dependencies it outputs nothing, but just from reading it I can see an issue.

The logic you want to execute when the input value changes needs to go inside the handleChange method you are trying to call here onChange={this.handleChange} .

For reference, these type of input fields are called Controled Components and you can read more about them in the React Documentation .

You code is not up to the mark. You are doing many mistakes in your code.

I have corrected all your code and here is the working solution of handler function https://react-t3luq3.stackblitz.io .

index.js

import React from 'react'
import ReactDom from "react-dom";
import Hello from './Hello';

ReactDom.render(<Hello />, document.getElementById("root")); 

Hello.js

import React, { Component, Fragment } from 'react'
import { Form } from 'semantic-ui-react'
import _ from 'lodash'

export default class Hello extends Component{

  constructor(props){
    super(props);
  }
  handleChange = e => {
    console.log(e.target.value)
  }

  render(){
  const { stateData } = this.props;

  let warningMessage = ''

  if (stateData) {
    let list = []
    if (props.values.injured_worker_type === 'Seasonal') {
      list = stateData.calculation_warnings['Seasonal']
    } else {
      list = stateData.calculation_warnings[`FullTime-${props.values.working_days}`]
    }

    const keys = _.keys(list)
    const index = _.findIndex(keys, key => {
      const fromValue = Number(key.slice(1, key.indexOf('-')))
      const toValue = Number(key.slice(key.indexOf('-') + 1, key.length))
      return props.values.total_days_paid >= fromValue && props.values.total_days_paid < toValue
    })

    if (index >= 0) {
      warningMessage = list[keys[index]]
    }
  }

  const message = warningMessage ? (
    <p style={{ color: 'red', fontSize: '0.85rem' }}> {warningMessage} </p>
  ) : null
  return (
    <Fragment>
      <Form.Group grouped style={{ marginTop: '2rem' }}>
        <label style={{ fontSize: '0.85rem' }}>8. Total days in preceeding 52 weeks:</label>
        <Form.Input
          name="total_days_paid"
          onChange={this.handleChange}
          width="6"
          placeholder="200"
          required
        />
      </Form.Group>
        {message}
    </Fragment>
  )
}
}

index.html

<html>
  <body>
    <div id="root"></div>
  </body>
</html>

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