簡體   English   中英

如何從組件外訪問react-native組件?

[英]How can i access react-native component from out of component?

我正在嘗試從組件外的函數訪問React-native組件的文本輸入。 我想通過clearForm()函數中的refs清除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();
  }
}

您需要將ref屬性設置為一個函數。 在此處查看文檔:

https://facebook.github.io/react-native/docs/direct-manipulation.html

ref={ input => this.myInput = input }

實際上,在該文檔中確實有一個示例: https : //snack.expo.io/? session_id = snack-session- HylUL01kbf

嘗試使用組件引用名稱作為道具,如下所示:

this.refs.email.setNativeProps({text: ''});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM