无法使用 this.refs 获取输入类型的值... 如何从输入类型获取该值
export class BusinessDetailsForm extends Component {
submitForm(data) {
console.log(this.refs.googleInput.value)
}
}
reder() {
return(
<form onSubmit={this.submitForm}>
<Field type="text"
name="location"
component={GoogleAutoComplete}
id="addressSearchBoxField"
ref="googleInput"
/>
</form>
)
}
}
最佳答案
您应该避免 ref="googleInput"
,因为它现在被视为旧版。你应该声明
ref={(googleInput) => { this.googleInput = googleInput }}
在处理程序内部,您可以使用 this.googleInput
来引用该元素。
然后在您的 submitForm
函数中,您可以使用以下命令获取文本值
this.googleInput._getText()
字符串引用是遗留的 https://facebook.github.io/react/docs/refs-and-the-dom.html
If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.
编辑
从React 16.3开始,创建引用的格式为:
class Component extends React.Component
{
constructor()
{
this.googleInput = React.createRef();
}
render()
{
return
(
<div ref={this.googleInput}>
{/* Details */}
</div>
);
}
}
关于javascript - 如何在reactjs中使用this.refs从输入类型获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137275/