Resetting Values in ReactDOM Ref children (Best Practices?)

大城市里の小女人 提交于 2020-01-05 05:49:07

问题


I've got a stateless component, called FlexibleInput.

import React, { PropTypes } from 'react'

export default function FlexibleInput({
  id,
  label,
  defaultValue,
  type,
  onChange,
}){
  let fieldClass = `${id}-field`
  return (
    <fieldset className={fieldClass}>
      <label htmlFor={id}>{label}</label>
      <input
        key={id}
        id={id}
        type={type}
        defaultValue={defaultValue}
        onChange={onChange}
        />
    </fieldset>
  )
}

FlexibleInput.propTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  defaultValue: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired, // accepts "text", "password" atm.
  onChange: PropTypes.func.isRequired,
}

I use this FlexibleInput in a form called AddNote.

<form
  className="note-list__add-note"
  onSubmit={this.addNote}
  ref={`${this.props.type}-addNoteForm`}
  >
  <FlexibleInput
    id="note"
    label="Awaiting changes..."
    type="text"
    defaultValue=""
    onChange={(e) => this.setState({ content: e.target.value })}
    />

After submitting using the this.addNote function... I would like to be able to reset the FlexibleInput input value.

I've managed to do a ugly ass hack version...

this.refs[`${this.props.type}-addNoteForm`]
  .childNodes[0].childNodes[1].value = ''

Which manages to properly reset the value. This is prone to change because perhaps the structure of the FlexibleInput will change? I do not know, hopefully not.

But my main question is, is there a way that I could do a sort of

this.refs[bla bla].find(#input)

or so?

It is not very clear in the React/ReactDOM documentation which api is available for a ref.

Thank you!


回答1:


You could create a Controlled component whereby the value of the input is set using using component state:

<form
  className="note-list__add-note"
  onSubmit={this.addNote}
  ref={`${this.props.type}-addNoteForm`}
  >
  <FlexibleInput
    id="note"
    label="Awaiting changes..."
    type="text"
    defaultValue=""
    value={this.state.content}
    onChange={(e) => this.setState({ content: e.target.value })}
  />

Then you just need to reset the content value within the this.addNote method:

addNote() {
  this.setState({ content: '' });
}

N.B. Ensure you bind addNote correctly to ensure this.setState is correctly referenced.



来源:https://stackoverflow.com/questions/40795121/resetting-values-in-reactdom-ref-children-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!