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

时间:2017-08-24 13:22:18

标签: reactjs react-native textinput expo

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

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的引用

2 个答案:

答案 0 :(得分: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中。此组件使用componentDidMount将注意力集中在autoFocus={true}上。

答案 1 :(得分:1)

我仍然不知道为什么系统会锁定&#39;每当我试图控制记录字段时ref ...但是我确实解决了我的问题,实际上正在我需要的参考。所以不确定这个问题是否已经解决了#39;本身,但我确实学到了一些东西。

相关问题