【问题标题】:React-Native: Access TextField value in another classReact-Native:在另一个类中访问 TextField 值
【发布时间】:2019-08-12 07:31:30
【问题描述】:

作为一名 iOS 开发人员,我在 react native 方面有点挣扎。

我在不同的类中有两个组件:

组件 A 是一个带有 TextInput 的视图

class A extends Component<Props>{
    state = {
        textFieldValue: ""
    };  
    render() {
        return (
            <View>
                <TextInput placeholder={this.props.placeholderText}
                            ref={textField => {
                                this.textField = textField;
                            }}
                            value={this.state.textFieldValue}
                            onChange={e => this.setState({ textFieldValue: e.target.value})}/>
            </View>
        );}
}

组件 B 在其视图中使用 A

class B extends Component<Props>{
        render() {
            return (
                <View>
                   <A placeholder={"test"}/>
                   <TouchableOpacity onPress={() => {
                                //show text of input A here
                            }}>
                        <View>
                            <Text>{text}</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            );}
    }

如何使用来自 BA 中的 TextInput 的值访问值/状态以在按下按钮时显示它?

【问题讨论】:

标签: javascript ios react-native textinput


【解决方案1】:

在 B 类上试试这个

    class B extends Component<Props>{
  render() {
      return (
          <View>
             <A placeholder={"test"} ref={c => this.textRef = c}/>
             <TouchableOpacity onPress={() => {
                          //show text of input A here
                          alert(this.textRef.state.textFieldValue)
                      }}>
                  <View>
                      <Text>{text}</Text>
                  </View>
              </TouchableOpacity>
          </View>
      );}
}

通过 ref props 访问 A 类的引用,然后得到它自己的状态。

【讨论】:

  • 这也是我的猜测,但它返回 undefined
  • 好的,我使用 onChange 而不是 onChangeText... 现在可以使用了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-10
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
相关资源
最近更新 更多