使用react.Createref()从inputText获取值
而不是每当“< inputText style {...}>”时重新渲染整个组件-tree。已更改,我试图在我的类组件中使用REF。 (我使用的是带有Expo托管工作流程的React Native。)
使用REFS,键入的文本在InputText字段中应出现。 但是,当按下按钮时,应记录键入文本的值(输入文本的值),但事实并非如此。
export class Feed extends Component {
constructor(props){
super(props);
this.state = {
//some state variables
}
this.myTextFromInput = React.createRef()
}
我首先创建MyTextFrominput Ref(上图)。
<TextInput
style={{height:100}}
ref={this.alias}
placeholder="Input Text Here"
/>
然后,我在InputText组件中使用了MyTextFrominput Ref。最后,按钮!
<Button onPress={()=>console.log(this.myTextFromInput.current.value)}>Press me!</Button>
这给了我未定义的
。我还尝试了this.mytextfrominput.value
和一个.getText()方法。
如何获得输入的文本?
更新: 终端日志未定义
。但是零食很好!?
Instead of re-rendering the entire component-tree whenever "<InputText style{...}>" is changed, I am trying to use refs in my Class Component. (I am using React Native with Expo managed workflow.)
Using refs, the typed text appears as it should in the InputText field.
But, when a button is pressed, the value of the typed text (value of the InputText) should be console logged, however it is not.
export class Feed extends Component {
constructor(props){
super(props);
this.state = {
//some state variables
}
this.myTextFromInput = React.createRef()
}
I started by creating the myTextFromInput ref (above).
<TextInput
style={{height:100}}
ref={this.alias}
placeholder="Input Text Here"
/>
I then used the myTextFromInput ref in the InputText component. And lastly, the button!
<Button onPress={()=>console.log(this.myTextFromInput.current.value)}>Press me!</Button>
This gives me undefined
. I have also tried this.myTextFromInput.value
and a .getText() method which is outdated.
How can I obtain the inputed text?
UPDATE:
Terminal log undefined
. But snack works fine!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有将正确的引用传递给
textInput
,它应该是this.mytextfrominput
notthis.alias
T忘了,无论您是否使用方法而不是箭头函数,都像我一样将其绑定到类实例。请参阅这个问题和此示例来自React Docs。
更新:
react.ref
在Android和iOS上似乎没有像在Web上工作的方式一样,您无法从输入中获得值组件不提供此属性,执行console.log(this.mytextfrominput.current)
您可以看到所有可用属性。 One solution from this question is to useYou aren't passing the correct reference to
TextInput
, it should bethis.myTextFromInput
notthis.alias
, take a look:Also don't forget that whether you use a method instead of arrow function you've to bind it to the class instance, like I did. See this question and this example from react docs.
Update:
React.ref
on Android and iOS doesn't seems to work as the same way as it works on web, you can't get the value from input because the component doesn't provide this property, doing aconsole.log(this.myTextFromInput.current)
you can see all the available properties. One solution from this question is to use TextInput from the package react-native-paper, as it provides the input value from the ref, or you could use the common state approach to store the input value, like so: