gpt4 book ai didi

javascript - react ref.example.value 与 e.target.value

转载 作者:行者123 更新时间:2023-11-30 15:44:28 28 4
gpt4 key购买 nike

我有以下组件可以与 this.refs.searchString.value 一起正常工作,但如果我只是 event.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>
)
}
})

最佳答案

如文档中所述,we shouldn't overuse refs , 首选方法是使用 event.target.value 使用 Controlled Components .

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>
)
}
})

关于javascript - react ref.example.value 与 e.target.value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301623/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com