【问题标题】:Print text entered in TextInput to console将 TextInput 中输入的文本打印到控制台
【发布时间】:2021-01-09 11:33:42
【问题描述】:

我想将 TextInput 中输入的值打印到控制台。

下面是我的代码中的 sn-ps:

constructor(props) {
        super(props);
        this.state= {
            textValue: "",
        }
    }
    _textChange = (text) => {
        this.setState({
            textValue: text,
        })
        console.log(this.state.textValue);
}

与:

<TextInput onChange={this._textChange.bind(this)}/>

我知道我的代码有问题,但我无法弄清楚。我只想在 TextInput 中打印输入的文本以在控制台中打印

注意

I have seen this answer。我无法理解给定链接中的答案。我对 react-native 很陌生。所以请尽量用简单的方式解释一下。

【问题讨论】:

  • 有什么动机在 onChange 中绑定方法?
  • 你可能想这样做:onChangeText={this._textChange} 而不是使用onChange

标签: reactjs react-native


【解决方案1】:

你应该使用 onChangeText 而不是 onChange

<TextInput onChangeText={this._textChange}/>

如果将您的方法声明为如下所示的命名函数

    _textChange(text) {
        this.setState({
            textValue: text,
        })
     }

所以你应该使用绑定,因为 this 关键字不会引用组件范围,但在你的情况下它不是必需的。

请看this的文章,了解命名函数和箭头函数的区别。

【讨论】:

  • 需要在onChangeText里面调用.bind(this)吗?
  • 因为你使用的是箭头函数所以没有必要
【解决方案2】:
任何组件中的

setState()函数都是异步或在调用它的函数完成后调用。如果你想在控制台看到结果,你可以这样做:

  this.setState({
       textValue: text,
    },() => {
        console.log(this.state.textValue);
    });

【讨论】:

    【解决方案3】:

    当你创建一个类时你遗漏了一些东西,但你的错误在反应事件onChangeText而不是onChange,但我认为你可以避免调用this._textChange.bind(this),这与另一种类型的类声明一起使用(见下文)。 我喜欢下面的 react 类声明,也许它可以帮助理解幕后发生的事情(如果你现在开始使用 react)

    class PComponern extends Component {
    
        constructor(props) {
            super(props);
            this.state= {
                textValue: "",
            };
           this._textChange = this._textChange.bind(this)
        }
     
      _textChange(text) {
        this.setState({
                textValue: text,
            });
        console.log(this.state.textValue);
      }   
    
      render (
        ...
        <TextInput onTextChange={this._textChange}/>
        ...
        )
       
    }
    

    这个表单可以帮助你开始,但有时在构造函数中没有必要调用this._textChange = this._textChange.bind(this),另见this reference

    还有一些评论暗示了以下几点

    • 您可能希望这样做:onTextChange={this._textChange} 而不是使用 onChange。

    Runnable code

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 2017-01-12
      • 2022-12-04
      • 2021-06-05
      • 2021-06-20
      • 2010-10-28
      • 2021-12-13
      相关资源
      最近更新 更多