2017-07-16 35 views
2

我用表单裁判,但现在我必须说明的形式,我现在面临一个问题,我要明确一个字段用户提交的东西之后。如何清除不受控制的领域反应

handleSumbit = (e) => { 
     e.preventDefault() 
     const todoText = this.state.todoText 
     if(todoText.length > 0){ 
      this.refs.todoTextElem = "" // wont work 
      this.props.onAddTodo(todoText) 
     } else { 
      this.refs.todoTextElem.focus() //worked 
     } 
    } 

    render() { 
     return(
      <div> 
       <form onSubmit={this.handleSumbit}> 
        <input ref="todoTextElem" type="text" onChange={e => this.setState({todoText: e.target.value})} name="todoText" placeholder="What do you need to do?" /> 
        <button className="button expanded">Add Todo</button> 
       </form> 
      </div> 
     ) 
    } 

清除ref根本不起作用,因为它是一个受控输入。我不想做一些愚蠢像

从父组件传递一个标志,告诉提交再使用的setState清除输入的形式。或使onAddTodo有一个回调,这样我可以做

this.props.onAddTodo(todoText).then(()=>this.state({todoText:""})) 

回答

3

的方式,您所使用的输入元素为uncontrolled,因为你没有使用的价值属性,意味着不控制它的价值。只需将该值存储在状态变量中即可。


你并不需要存储状态变量输入字段值,如果您使用的是refref将有DOM element参考,所以你需要使用this.refName.value访问该元素的值。

步骤:

写输入元素是这样的:

<input 
    ref= {el => this.todoTextElem = el} 
    type="text" 
    placeholder="What do you need to do?" /> 

为了得到它的价值:this.todoTextElem.value

2-明确不受控制输入字段,使用清除它的值:

this.todoTextElem.value = ''; 

写这样的:

handleSumbit = (e) => { 
    e.preventDefault() 
    const todoText = this.todoTextElem.value; 
    if(todoText.length > 0){ 

     this.todoTextElem.value = '';  //here 

     this.props.onAddTodo(todoText) 
    } else { 
     this.todoTextElem.focus() 
    } 
} 

另一个变化是关于string refs, As per DOC

如果你反应过来的工作,你可能熟悉的旧 API其中ref属性是一个字符串,如“为textInput”,和DOM 节点作为this.refs.t被访问extInput。我们建议不要这样做,因为 字符串参考文献有一些问题,被视为遗留问题,并且可能会在将来的某个版本中删除 。如果您目前使用 this.refs.textInput访问参考,我们建议您使用回调模式 。

+0

如果窗体有像复选框和单选按钮的东西的形式使用ref而不是状态是好的吗? –

+0

一般我们应该尽量避免使用ref,总是使用状态变量。请检查此文档中关于ref的说明:[何时使用参考](https://facebook.github.io/react/docs/refs-and-the-dom.html#when-to-use-refs)和[Don 't Overuse Refs](https://facebook.github.io/react/docs/refs-and-the-dom.html#dont-overuse-refs) –

+0

但是您在上面的表单中使用了ref? lol。如果你使用状态,如果你想清除输入的字段为空,意味着再有一个再显示。这很好吗?或者我已经过去担心表现? –

0

尝试使用功能,而不是裁判。请注意,裁判是一个DOM元素,这意味着你仍然需要解决其属性(.value)对它们进行修改,而不是试图直接覆盖的元素。 以下应该工作:

handleSumbit = (e) => { 
    e.preventDefault() 
    const todoText = this.state.todoText 
    if(todoText.length > 0){ 
     this.todoTextElem.value = "" 
     this.props.onAddTodo(todoText) 
    } else { 
     this.todoTextElem.focus() 
    } 
} 

render() { 
    return(
     <div> 
      <form onSubmit={this.handleSumbit}> 
       <input ref={input => this.todoTextElem = input} type="text" onChange={e => this.setState({todoText: e.target.value})} name="todoText" placeholder="What do you need to do?" /> 
       <button className="button expanded">Add Todo</button> 
      </form> 
     </div> 
    ) 
}