2017-04-03 169 views
1

我想在這樣一個搜索輸入使用onSearch事件:陣營未知道具「onSearch」

render(){ 
    return(

    <input type="search" onSearch={() => console.warn('search') } /> 
); 
} 

,但我得到了unknown prop error,如何解決它的任何想法?

我想創建一個自動完成輸入,當用戶點擊鍵盤上的「搜索」圖標時觸發一個事件。

編輯:

onSearch是不是一個標準的屬性,所以我想反應過來不會支持它。由於onSearch是一樣的擊打回車鍵,使用onkeypress事件將做的工作:

render() { 
    return (
    <main> 
     <input onKeyPress={ this.onKeyPress } type="search" list="options"/> 
     <datalist id="options"> 
     { OPTS.map(item => <option value={ item.nm } key={ item.id } data-id={ item.id } />) } 
     </datalist> 
    </main> 
    ); 
    } 


onKeyPress(event) { 
    if (event.key === 'Enter') { 
    const id = document.querySelector(`#options option[value="${event.target.value}"]`).dataset.id; 
    if (id) { 
     console.warn('user search', id); 
    } 
    } 
} 
+0

嘗試使用'onSubmit'或'onChange'而不是'onSearch'。 –

回答

0

我認爲你正在尋找onChange。輸入將在編輯其中的數據時觸發更改事件。

編輯: onSearch不支持React Docs您可以使用按鍵事件或鍵盤事件來做同樣的事情。只是檢查的鍵碼,看看它的輸入(13)

handleKeyPress = (e) => { 
    if(e.keyCode === 13) { 
     console.warn('search'); 
    } 
} 

<input type="search" onKeyPress={this.handleKeyPress} /> 
+0

不,每次用戶在我的輸入中寫入內容時都會觸發onchange,我希望僅當用戶單擊鍵盤上的「搜索」圖標時纔會觸發事件。 – IagoLast

+0

@lagoLast我明白你在說什麼了。如果您願意,我可以編輯我的答案以顯示如何使用onChange爲onSubmit工作 –

0

我覺得這樣的事情應該工作:

constructor() { 
    this.state = { userInput: "" }; 

    this.handleSubmit = this.handleSubmit.bind(this); 
} 

handleSubmit() { 
    console.warn('user search', this.state.userInput); 
} 

render() { 
    return (
    <form onSubmit={handleSubmit}>  
     <input 
     onChange={e => this.setState({userInput: e.target.value})} 
     type="search" 
     list="options" 
     value={this.state.userInput} 
     /> 
     <datalist id="options"> 
     { OPTS.map(item => <option value={ item.nm } key={ item.id } data-id={ item.id } />) } 
     </datalist> 
    </form> 
); 
} 

看看https://facebook.github.io/react/docs/forms.html。您可能想要使用受控組件,而不是直接訪問DOM以獲取輸入值。

0

search絕對是搜索類型爲input的DOM事件,但反應並不支持它。 所以你可以聽原始DOM元素事件。

做這樣

<Input 
    ref={element=>(element||{}).onsearch=this.searchHandler} 
/> 

這可以工作,你可能想知道爲什麼。

首先,ref屬性接受一個函數作爲一個值,它將與一個真正的dom元素(與虛擬dom相對)執行。

在真正的dom被掛載到文檔之前,函數也會被執行,但沒有可以附加事件的元素,所以我們使用(element||{})來避免錯誤。

而不是使用addEventListener的,我們使用ele.onsearch方式,因爲該組件將重新描繪時的道具或狀態更新,每個渲染函數被調用時,我們將一個事件時search觸發的事件處理函數可以附加到DOM元素跑幾次。