首页 > 解决方案 > 如何在另一个文件中获取组件的状态反应本机

问题描述

我一直试图弄清楚这一点,但我似乎不太明白如何做到这一点。
我有一个本质上是一个表单的屏幕,但所有组件都存在于不同的文件中(像往常一样)。而我无法掌握的(我在网上搜索过类似的查询:How to get state of custom react component from parent和类似的东西,我想不出任何东西)是如何获取状态更改函数所在的组件的状态不同的文件。据我了解,react-native 中没有 DOM 操作,因为我在网络上执行此操作的方式如下:

const stateValue = document.querySelector('#thingIWantToGetTheValueOf').value;

但据我所知,你不能在原生反应中做到这一点。以下是我正在使用的代码,然后我将其缩减为一个问题:

// SubmitReferralScreen.js
      <PageTemplate headerText='New Referral' needsBackButton='true' navBar='true' needsFocus='Referrals'>
            <KeyboardAvoidingView behavior='padding' style={styles.formContainer}>
              <View style={styles.inputContainer}>
                <GeneralInput autoFocus='true' labelText='Referral Name' type='default' placeholder='Full Name' />
                <GeneralInput labelText='Phone Number' type='phone-pad' placeholder='(555) 123-4567' />
                <Picker selectedValue={this.state.relationship} onValueChange={(itemValue, itemIndex) => this.setState({relationship: itemValue})} style={styles.picker}>
                  <Picker.Item label='Friend' value='friend' />
                  <Picker.Item label='Family Member' value='family' />
                  <Picker.Item label='Select' value='' />
                  <Picker.Item label='Co Worker' value='coworker' />
                </Picker>
                <GeneralInput labelText='Email' type='email-address' placeholder='email@shinesolar.com' />
              </View>
              <IconButton navigateTo='YayReferral' buttonText='Submit Referral' />
            </KeyboardAvoidingView>
      </PageTemplate>


// GeneralInput.js
export class GeneralInput extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            placeholder: this.props.placeholder,
            inputValue: "",
            inputting: false,
        };
     }
    whenInputIsFocused() {
        this.setState({placeholder: ""});
    }
    whenInputIsBlurred() {
        if (this.state.inputValue === "") {
            this.setState({placeholder: this.props.placeholder});
        }
    }
  render() {
    const autoFocus = this.props.autoFocus == 'true';
    return(
        <View style={styles.outerContainer}>
            <Text style={styles.labelText}>{this.props.labelText}</Text>
            <TextInput 
                autoCapitalize='none' 
                autoFocus={autoFocus}
                onChangeText={(inputValue) => this.setState({inputValue})}
                value={this.state.inputValue} 
                secureTextEntry={this.props.secureTextEntry} 
                onBlur={this.whenInputIsBlurred.bind(this)} 
                onFocus={this.whenInputIsFocused.bind(this)} 
                underlineColorAndroid="transparent" 
                keyboardType={this.props.type} 
                returnKeyType={this.props.returnKeyType} 
                placeholder={this.state.placeholder} 
                placeholderTextColor='rgba(255, 255, 255, 0.3)' 
                style={styles.inputStyles} />
        </View>
    );
  }
}

在 SubmitReferralScreen 中,IconButton按下该按钮时,我想收集所有 GeneralInputs(和选择器)的值,并在它们通过某些验证时提交表单。但是,由于状态更改函数保存在 GeneralInput.js 中,我不知道如何访问这些组件的状态。 您如何访问从另一个文件夹导入的组件的状态?

标签: javascriptreact-native

解决方案


为此,您<GeneralInput>需要在您的组件中实现一个函数,该函数将数据传回并在您的父级中设置有状态信息。

然后,您可以决定在哪里管理 的状态GeneralInput,它只是在哪里将值(在状态更改时)传回给父级,或者是否由父级管理。

此外,我相信您可以在场上使用ref并将其传回,但这并不是我真正推荐的方式。

在您的父控制器中:

<GeneralInput
   autoFocus='true'
   labelText='Referral Name'
   type='default'
   placeholder='Full Name'
   onChange={this.handleChange} //added line
 />

// class method outside of render
onChange = ({key, value}) => { 
    this.setState({key, value});
}

// GeneralInput.js

<TextInput 
  onChangeText={this.storeValue}
  ...
/>

//outside of render method
storeValue = (inputValue) => {
   this.setState({inputValue})
   this.props.onChange({key: 'myField', value: inputValue})
} 

同样,我完全不建议这样做。自上而下的担忧意味着您需要将事情管理得更高,或者使用诸如 mobx/redux 之类的东西来进行通信,而不是管理它。此外,如果你这样做,我会让你的父母而不是孩子的真相来源,并相应地传递价值。


推荐阅读