如何在 reactjs 中使用 this.refs 从输入类型中获取值? [英] How to get values from input types using this.refs in reactjs?
问题描述
无法使用 this.refs 获取输入类型的值...如何从输入类型中获取该值
导出类 BusinessDetailsForm extends Component {提交表单(数据){控制台日志(this.refs.googleInput.value)}}红人(){返回(<form onSubmit={this.submitForm}><字段类型="文本"名称=位置"组件={GoogleAutoComplete}id="地址搜索框字段"参考 =谷歌输入"/></表单>)}}
你应该避免 ref="googleInput"
因为它现在被认为是遗留的.你应该声明
ref={(googleInput) =>{ this.googleInput = googleInput }}
在处理程序内部,您可以使用 this.googleInput
来引用元素.
然后在您的 submitForm
函数内部,您可以使用this.googleInput._getText()
字符串引用是遗留的https://facebook.github.io/react/docs/refs-and-the-dom.html
<块引用>如果您之前使用过 React,您可能熟悉旧 API,其中 ref 属性是一个字符串,如textInput",并且 DOM 节点作为 this.refs.textInput 访问.我们建议不要这样做,因为字符串引用存在一些问题,被认为是遗留的,并且可能会在未来版本之一中被删除.如果您当前正在使用 this.refs.textInput 来访问 refs,我们建议您改用回调模式.
编辑
从 React 16.3 开始,创建 refs 的格式是:
class Component 扩展了 React.Component{构造函数(){this.googleInput = React.createRef();}使成为(){返回(<div ref={this.googleInput}>{/* 细节 */}
);}}
Not able to get values of input type using this.refs... how to get that values from input type
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>
)
}
}
You should avoid ref="googleInput"
as it is now considered legacy. You should instead declare
ref={(googleInput) => { this.googleInput = googleInput }}
Inside of your handler, you can use this.googleInput
to reference the element.
Then inside of your submitForm
function, you can obtain the text value with
this.googleInput._getText()
String refs are legacy 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.
Edit
From React 16.3, the format for creating refs are:
class Component extends React.Component
{
constructor()
{
this.googleInput = React.createRef();
}
render()
{
return
(
<div ref={this.googleInput}>
{/* Details */}
</div>
);
}
}
这篇关于如何在 reactjs 中使用 this.refs 从输入类型中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!