javascript - 从组件访问表单控件值

标签 javascript reactjs

我有一个表格:

<form onSubmit={this.onSubmit}>
  <input ref="name" type="text" />
  ...
  <select ref="pet">
    <option>Dog</option>
    <option>Cat</option>
  </select>
</form>

在另一个地方,我有不同的表单,具有不同的输入,但具有相同的选择。我可以简单地从第一个代码中绑定(bind)复制代码,但我不想这样做。

我想制作一个组件。就用户界面而言,我知道它会起作用。但是,我不知道在这种情况下如何访问 this.refs.pet.value:

<form onSubmit={this.onSubmit}>
  <input ref="name" type="text" />
  ...
  <PetsSelect ??????? />
</form>

如何从组件的父级(窗体)中访问选择框的值?

最佳答案

非常快速的写作示例

class PetsSelect extends React.Component {

  get value(){
    return this.state.value
  }

  handleChange(key, value){
    this.setState({[key]: value})
    this.props.onChange && this.props.onChange(key, value)
  }

  constructor(props){
    super(props)
    this.state = { value: props.value || '', name: '' }
  }

  render(){
    // add the name etc and then you can handleChange('name', ...) 
    // or make it more DRY
    return <div>
      <select 
        ref={select => this.select = select} 
        value={this.state.value} 
        onChange={e => this.handleChange('value', e.target.value)}>
        <option value=''>Please select</option>
        <option value='dog'>Dog</option>
        <option value='cat'>Cat</option>
      </select>
    </div>
  }
}


class Form extends React.Component {
  handleSubmit(e){
    e.preventDefault()
    console.log(this.pets.value)
  }
  render(){
    // this.pets becomes the instance of the PetsSelect class.
    return <form onSubmit={e => this.handleSubmit(e)}>
      <PetsSelect ref={pets => this.pets = pets} />
      <button type='submit'>try it</button>
    </form>
  }
}

ReactDOM.render(<Form />, document.getElementById('app'))

请参阅此处:https://codepen.io/anon/pen/WExepp?editors=1010#0 。基本上,您可以: onChange 并获取父级中的值,或者在需要时读取子级的值。

请记住你说的是“受控” - 我没有做任何事情来保持 props.valuestate.value - 在不受控制的情况下,你会使用 默认值

关于javascript - 从组件访问表单控件值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45440602/

相关文章:

javascript - 将 GA 事件添加到可重用的 React 组件中

javascript - 在默认 gulp 任务中使用询问器

javascript - 每天发送邮件

javascript - 如何使用 Fetch 将附加数据从客户端 Stripe Checkout 传递到服务器

javascript - 在Webpack4中设置./src的路径?

reactjs - 没有 withStyles 的 material-ui@next?

javascript - 当我在 firefox 浏览器下点击它时,contenteditable 会触发模糊事件

JavaScript 对整个元素类的高效样式更改

javascript - Babel 已经做了 Object.create(superClass.prototype) 为什么还要用 setPrototypeOf 来继承?

javascript - response.json() 中的值计数来自哪里?