2016-09-27 56 views
3

我有下面的輸入字段,我需要輸入輸入並將其傳遞給下面顯示的按鈕的onClick事件。將反應文本字段輸入值作爲參數傳遞給方法

<input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/> 
<input type="text" style = {textFieldStyle} name="payloadBox" placeholder="Enter payload here..."/> 
<button value="Send" style={ buttonStyle } onClick={this.publish.bind(this,<value of input field 1>,<value of input field2>)}>Publish</button><span/> 

我有一個方法稱爲發佈,它需要兩個字符串參數。代替這些字符串,我需要傳遞在輸入字段中輸入的值。如何在不將狀態值存儲的情況下實現這一點?我不想將輸入字段值存儲在狀態變量中。任何幫助將非常感激。

回答

2

如何在不存儲狀態值的情況下實現這一目標?

我認爲在這種情況下,更好的使用狀態

class App extends React.Component { 
 
    constructor() { 
 
    super(); 
 
    this.state = { 
 
     topicBox: null, 
 
     payloadBox: null 
 
    }; 
 
    
 
    this.publish = this.publish.bind(this); 
 
    this.handleChange = this.handleChange.bind(this); 
 
    } 
 
    
 
    handleChange({ target }) { 
 
    this.setState({ 
 
     [target.name]: target.value 
 
    }); 
 
    } 
 

 
    publish() { 
 
    console.log(this.state.topicBox, this.state.payloadBox); 
 
    } 
 
    
 
    render() { 
 
    return <div> 
 
     <input 
 
     type="text" 
 
     name="topicBox" 
 
     placeholder="Enter topic here..." 
 
     value={ this.state.topicBox } 
 
     onChange={ this.handleChange } 
 
     /> 
 
     
 
     <input 
 
     type="text" 
 
     name="payloadBox" 
 
     placeholder="Enter payload here..." 
 
     value={ this.state.payloadBox } 
 
     onChange={ this.handleChange } 
 
     /> 
 
     
 
     <button value="Send" onClick={ this.publish }>Publish</button> 
 
    </div> 
 
    } 
 
} 
 

 
ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container"></div>

+1

我認爲這是最好的辦法。我會[避免使用參考](http://stackoverflow.com/questions/29503213/use-state-or-refs-in-react-js-form-components) –

2

您可以添加裁判對每個文本字段,並讀取它的價值,如:

class App extends React.Component { 
    constructor() { 
    super(); 
    this.publish = this.publish.bind(this); 
    } 

    publish(topicBox, payloadBox) { 
    alert(this.refs.topic.value); 
    alert(this.refs.payload.value); 
    } 

    render() { 
    return <div> 
     <input 
     ref="topic" 
     type="text" 
     name="topicBox" 
     placeholder="Enter topic here..."/> 

     <input 
     ref="payload" 
     type="text" 
     name="payloadBox" 
     placeholder="Enter payload here..."/> 

     <button 
     value="Send" 
     onClick={this.publish}> 
     Publish 
     </button> 
    </div> 
    } 
} 

ReactDOM.render(<App />, document.getElementById('container')); 

工作小提琴https://jsfiddle.net/hjx3ug8a/15/

感謝您對Alexander T的支持!

+0

當我使用refs時出現以下錯誤。 ./src/components/Sender.tsx中的錯誤 (126,102):錯誤TS2339:類型'{[key:string]'上不存在屬性'topic':組件 |元件; }」。 – mayooran

+0

它應該工作,添加整個腳本以查看問題出在哪裏。 –

+0

@mayooran我更新了答案! –

相關問題