首页 文章

React Native TextInput引起奇怪的崩溃/锁定

提问于
浏览
1

我正在尝试在React Native中做一些 TextInput 焦点内容并且需要引用TextInput的 ref 属性...但是当我尝试console.log输入引用时,得到一些奇怪的行为(运行Expo XDE)整个事情变慢,好像有一些奇怪的记忆循环 . 代码如下 .

export default class MyComponent extends React.Component {
  constructor() {
    super();
    this.setInputRef = this.setInputRef.bind(this);
  }
  // function where i want to set or access the input ref
  setInputRef(input) {
    console.log('This log message is fine');
    console.log('This log message is not fine:', input); // locks up here
  }

  render() {
    return (
      <View>
            <TextInput ref={input => this.setInputRef(input)} />
      </View>
    );
  }
}

有任何想法吗?不确定这是否是本机问题 . 基本上我试图调用另一个函数传入并在我的 setInputRef 函数期间调用,以便父组件可以知道此textinput的ref

2 回答

  • 1

    您不需要使用ref来执行此操作,您可以使用此代码执行您想要的操作:

    export default class MyComponent extends React.Component {
      state = {text: ''}
    
      _setValue = (text) => this.setState({text})
    
      render () {
        return (
          <View>
            <TextInput
              autoFocus={true}
              onChangeText={this._setValue}
              value={this.state.text}
            />
          </View>
        )
      }
    }
    

    在这种情况下, TextInput 值存储在 this.state.text 中 . 此组件通过使用 autoFocus={true} 将输入集中在 componentDidMount 上 .

  • 1

    我仍然没有't know why the system '锁定' whenever I am trying to console log the field' s ref ...但是我确实解决了我的问题,这实际上得到了我需要的参考 . 所以不确定这个问题本身是否是'solved',但我确实学到了一些东西 .

相关问题