2016-06-12 109 views
0

陣營參考文獻我有以下JSX:捕獲由事件

import React, {Component} from 'react'; 

class Register extends Component { 
    handleSubmit(){ 
     console.log("hey!") 
    } 

    setHandles(c){ 
     //This never executes. 
     console.log("foo"); 
    }  

    render() { 
     return (
<form className='form-horizontal' onSubmit={this.handleSubmit}> 
    <h4>Create a new account.</h4> 
    <hr />   
    <div className="form-group"> 
     <label htmlFor="Email" className="col-md-2 control-label">User Name</label> 
     <div className="col-md-10"> 
      //******************************** 
      //**** USING SETHANDLES HERE ***** 
      //******************************** 
      <input type="email" className="form-control" ref="{this.setHandles}" /> 
      <span className="text-danger"></span> 
     </div> 
    </div> 
    <div className="form-group"> 
     <label htmlFor="Password" className="col-md-2 control-label">Password</label> 
     <div className="col-md-10"> 
      //******************************** 
      //**** USING SETHANDLES HERE ***** 
      //******************************** 
      <input type="password" className="form-control" ref="{this.setHandles}" /> 
      <span className="text-danger"></span> 
     </div> 
    </div> 
... 

setHandles功能永遠不會執行。爲什麼?

我的意圖是給每個input屬性ref="{this.setHandles}"以便setHandles回調可以註冊每個對應的DOM元素。之後,當我準備發佈表單時,我可以遍歷DOM元素數組以獲取相應的輸入值。

回答

2

這不是調用你的函數,因爲你正在傳遞字符串,remove the quote marksref={this.setHandles}

但是,實現您想要的更好的方法是將onChange事件分配給每個輸入,以便將值存儲在您的狀態中。

像這樣

constructor(props){ 
    this.onChange = this.onChange.bind(this); 
    this.onSubmit = this.onSubmit.bind(this); 
} 
onSubmit(){ 
    console.log(this.state); // You got your input values here 
} 
onChange(e){ 
    this.setState({[e.target.name] : e.target.value}); 
} 
render(){ 
    return <div><form> 
    <input type="text" name="mail" className="form-control" 
    onChange={this.onChange} /> 
    <input type="text" name="password" 
    className="form-control" ref={this.setHandles} onChange={this.onChange} /> 
    <button onClick={this.onSubmit}>Submit</button> 
    </form></div> 
} 

full working example

+0

刪除引號。嘆。這正是我厭倦編程時所得到的結果。另外,非常感謝泛型onChange想法。 –

0

setHandles函數永遠不會運行,因爲它沒有理由;它沒有被調用,並且在沒有()的JSX中的函數不會運行,除非他們被要求。

我建議把你的需要的功能到componentDidMount() react方法,所以它看起來像這樣:

class Register extends Component { 
    componentDidMount() { 
    // Do the thing 
    } 

    render() { 
    ... 
    } 
} 

這裏的作出反應的doc它:https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

+1

REF是一個特殊的處理程序中的反應是,用於當該子組件被呈現給取的子組件的DOM元素。見[這裏](https://facebook.github.io/react/docs/more-about-refs.html)。 –