从父级传递给子级onChange函数,该函数不起作用

时间:2018-10-16 07:49:50

标签: javascript reactjs events

有一个具有handleChange函数的父组件,我将该函数传递给子组件。

并提供给输入文件,那么输入文件存在错误,我根本无法更改值。

ParentComp:

 handleChange = (e, data) => {
    if (data && data.name) {
      this.props.setFieldValue(data.name, data.value)

      if (data.name === 'pay_rate') {
        console.log('PAY_RATE: ', data)
      }
    }
  }


  return (
    <Grid.Column width={8}>
      <Segment raised>
        <Header>
          <p style={{ fontSize: '1.2rem' }}>
            Church Mutual Worker\'s Compensation Claim
            <span style={{ float: 'right' }}>{`Claim #${props.claim.claimNumber}`}</span>
          </p>
        </Header>

        <Form onSubmit={handleSubmit}>

    // Here called is Child component
            <EditStandaloneClaimDetails
            claim={props.claim}
            loading={loading}
            handleChange={props.handleChange}
            />    
        </Form>
      <Comment currentClaim={props.currentClaim} />
    </Segment>
  </Grid.Column>
)

ChildComponent:

const EditStandaloneClaimDetails = ({ handleChange, claim, loading, testChange }) => {
  if (!claim || loading) {
    return null
  }

  const { noticeOnly, recieveDate, accountNumber } = claim

  return (
    <Segment
      raised
      style={{
        backgroundColor: '#F0F0F0',
      }}
    >
      <h5>Claim Details</h5>
      <Form.Group >

        <Form.Field>
        // CANNOT ENTER A NEW VALUE FOR DATE INPUT FILED
          <label>Date Received</label>
          <DateInput
            name={'recieveDate'}
            placeholder="Date received"
            value={recieveDate}
            onChange={handleChange}
            style={{ width: '65%' }}
            dateFormat={'MM/DD/YYYY'}
          />
        </Form.Field>

       </Form.Group >

此属性值= {recieveDate}中可能存在问题吗?

1 个答案:

答案 0 :(得分:1)

您可以使用回叫功能来处理它。

在您的父组件中,替换以下行:

handleChange = (e, data) => {
 //here you get the updated date 
 //add your logic
}

// Here called is Child component

<EditStandaloneClaimDetails
   recieveDate = {'your date'}
   claim={props.claim}
   loading={loading}
   handleChange={(event, data) =>this.handleChange(event,data)}
  />    

子组件中添加以下功能,该功能负责回调父组件。

constructor(props){
  super();
  this.state = { recieveDate: prop.recieveDate };
}

HandleChange(event,value){
   this.setState({ recieveDate})
    this.props.handleChange(value,event.uid);
}

<DateInput
        name={'recieveDate'}
        placeholder="Date received"
        value={recieveDate}
        onChange={(event, value) =>this.HandleChange(event,data)}
        style={{ width: '65%' }}
        dateFormat={'MM/DD/YYYY'}
      />