javascript - 如何从组件外访问 react native 组件?

标签 javascript react-native

我正在尝试从组件外的函数访问 React-native 组件的文本输入。我想通过 clearForm() 函数中的引用清除 TextInput。

MyComponent.js

import React, { Component } from 'react';
import { 
  View,
  TextInput,
} from 'react-native';

class myComponent extends Component {
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          ref= {'email'}
          style={styles.input}
          placeholder="Email"
        />
      </View>
    );
  }
}

Actions.js

function clearForm(data){
  for(var input_name in data){
    /////???
    //this.refs[input_name].setNativeProps({text: ''});
  }
}

最佳答案

很抱歉花了这么长时间,但这应该有效:

// myComponent.js
class myComponent extends Component {

  constructor(props) {
    this.state = { 
      emailText: ''
    }
  }

   clearField() { 
    this.setState({ 
      emailText: ''
    })
   }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          ref= {'email'}
          style={styles.input}
          placeholder="Email"
          value={this.state.emailText}
        />
      </View>
    );
  }
}

// Actions.js
function clearForm(data){
  for(var input_name in data){
    this.refs[input_name].clearField();
  }
}

关于javascript - 如何从组件外访问 react native 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47594752/

相关文章:

javascript - 如何获得 overflow hidden 的加载链接并在悬停时显示完整内容?

javascript - N 个排序整数数组的交集有限制

ios - AlertIOS.prompt for numeric 输入

reactjs - React 和 Redux 工具包 - promise 后拒绝

javascript - npx react-native init 错误在 appdata 文件夹中不包含 package.json 文件

react-native - 在 React Native 中使用多行自动增长文本输入

Javascript 没有正确执行程序

javascript - 如何在 wordpress 前端使用 ajax 保存帖子和自定义字段值?

javascript - JW 播放器 : No suitable players found

javascript - 如何衡量我的应用程序在 React Native 中的数据使用情况?