2016-10-28 71 views
0

我有下面的組件可以很好地與this.refs.searchString.value工作,但它會工作,如果我只是event.target.value而不是?如果是這樣,哪一個是首選的方法?每個人的優點和缺點是什麼?react ref.example.value vs. e.target.value

const SearchBar = React.createClass({ 

    handleSubmit (event) { 
    event.preventDefault() 
    const formattedSearchString = this.refs.searchString.value.replace(/[^a-z]/gi, "").toLowerCase() 
    this.refs.searchString.value = '' 
    this.props.submitSearch(formattedSearchString) 
    }, 
    render() { 
    return (
     <form className="form form-group has-info col-md-4 text-align-center" onSubmit={this.handleSubmit}> 
     <input className="search-input form-control" type="text" ref="searchString" placeholder=" . . . enter pokemon name" /> 
     <button className="btn btn-info btn-raised" type="submit" name="button">Search!</button> 
     </form> 
    ) 
    } 
}) 
+0

'event.target.value'是首選。不要過度使用參考文獻。 https://facebook.github.io/react/docs/refs-and-the-dom.html#dont-overuse-refs –

回答

0

由於文檔是we souldn't overruse refs中提到,它是利用者優先向Controlled Components使用event.target.value

const SearchBar = React.createClass({ 
    getInitialState(){ 
    return {textValue: ""}; 
    }, 
    onTextChange(evt) { 
    this.setState({textValue: evt.target.value}); 
    }, 
    handleSubmit (event) { 
    event.preventDefault() 
    const formattedSearchString = this.state.textValue.replace(/[^a-z]/gi, "").toLowerCase() 
    this.refs.searchString.value = '' 
    this.props.submitSearch(formattedSearchString) 
    }, 
    render() { 
    return (
     <form className="form form-group has-info col-md-4 text-align-center" onSubmit={this.handleSubmit}> 
     <input className="search-input form-control" type="text" value={this.state.textValue} onChange={this.onTextChange} placeholder=" . . . enter pokemon name" /> 
     <button className="btn btn-info btn-raised" type="submit" name="button">Search!</button> 
     </form> 
    ) 
    } 
})