2016-05-12 45 views
0

我想知道,什麼是最好的做法添加事件監聽器到一個DOM元素,這是不是呈現的反應(一個單選按鈕) 我有一個給定的HTML表單和我想使用react.js的優勢,而不是玩jQuery ajax的東西。react.js無事件監聽器反應元素

使用jQuery我會做這樣的事情:

$('input[type=radio][name=bedStatus]').change(function() {....} 

我應該使用這樣的反應有()

componentDidMount: function() { 
    if (this.props.onWindowScroll) window.addEventListener("scroll", this.handleScroll); 
}, 

componentWillUnmount: function() { 
    if (this.props.onWindowScroll) window.removeEventListener("scroll", this.handleScroll); 
} 

可能有人把我推在正確的方向?

乾杯啓

回答

0

對於反應通過您的組件創建的元素:的最佳實踐,

render() { 
    return (
    <div> 
     <input type="radio" onChange={this.handleChange} /> 
    </div> 
) 
} 

在術語通常非反應元件應爲windowdocument。如果它是一個HTML元素,那麼它可能應該被封裝在一個反應​​組件中,並且事件監聽器應該如上所述。

對於非反應元素,您的方法非常好。當組件卸載時刪除監聽器是非常重要的

監聽器通常連接組件被安裝後:

componentDidMount: function() { 
    if (this.props.onWindowScroll) window.addEventListener("scroll", this.handleScroll); 
} 

重要:刪除卸載時:

componentWillUnmount: function() { 
    if (this.props.onWindowScroll) window.removeEventListener("scroll", this.handleScroll); 
} 

我再說一遍,這通常是附着在windowdocument事件對象。

根據您的使用情況,可以接受父元素或子元素的HTML元素,甚至動態創建的某些元素。 findDOMNode()在某些情況下可能會有用。但建議儘可能避免這樣做。