2016-11-24 21 views
1

我有一個無狀態組件,名爲FlexibleInput。重置ReactDOM中的值參考兒童(最佳實踐?)

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, 
} 

我在稱爲AddNote的表單中使用此FlexibleInput。

<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 })} 
    /> 

使用this.addNote函數提交後...我希望能夠重置FlexibleInput輸入值。

我已經成功地做一個醜陋的屁股破解版...

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

管理着正確的重置價值。這很容易改變,因爲FlexibleInput的結構可能會改變?我不知道,希望不會。

但我的主要問題是,有沒有辦法,我可以做一個排序

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

左右?

React/ReactDOM文檔中不太清楚api是否可用於ref

謝謝!

<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 })} 
    /> 

然後你只需要在this.addNote方法內復位含量值:

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

回答

2

由此輸入的值採用組件狀態使用設置您可以創建一個Controlled componentNB確保正確綁定addNote以確保this.setState被正確引用。

+0

當我以前試過這個,它不會允許我編輯「值」,但現在(幾個月後)我正在這樣做,它按預期工作。不知道是否在我的最終或錯誤上存在錯誤,但使用受控組件似乎是一種方法!謝謝:) –

+0

你還記得你使用的是什麼版本的React嗎?無論哪種方式很高興我可以幫助! – Pineda

+0

不幸的不是。我相信這可能是因爲我沒有正確地約束狀態,並且仍在使用道具,所以沒有顯示「實時編輯」或更改爲輸入值。 –