【问题标题】:Pass state value as props react native传递状态值作为道具反应原生
【发布时间】:2021-09-21 23:14:30
【问题描述】:

我正在尝试制作一个可重用的文本输入组件,但我想获取用户键入的值以在 App.js 上对其进行操作

TextInputComponent.js

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

const TextInputComponent = (props) => {
  const [text, onChangeText] = useState("")

    return (
    <View>
      <TextInput style={styles.container} value={text} onChangeText={onChangeText} placeholder="Enter"/>
    </View>
    )
}


const styles = StyleSheet.create({
    container: {
      height: 50,
      width: 200,
      padding: 10,
      margin: 10,
      borderWidth: 1,
      borderColor: "black",
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
  });
  

export default TextInputComponent

App.js

import { StatusBar } from 'expo-status-bar';
import React, {useState} from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';
import TextInputComponent from './src/components/TextInputComponent';

export default function App() {

  return (
    <View style={styles.container}>
    <View style={{flexDirection: 'row' }}>
    <Text>Test</Text>
    <TextInputComponent/>
    <Button title="A" onPress={()=> console.log(-------> text value from TextInputComponent <-----)}></Button>
    </View>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

为了访问在 TextInputComponent.js 上创建的状态值,我需要做什么?

【问题讨论】:

  • 你必须去reactjs.org 阅读关于道具的信息。您在 component 参数中调用 props 并且没有使用它们。这不是基本的反应,它是必不可少的反应,如果你不知道怎么做,我建议一些 youtube 教程。

标签: react-native redux react-hooks state react-props


【解决方案1】:

您可以做的一件事是将自定义方法传递给组件,然后将其用作 onChangeText 方法:

const TextInputComponent = ({ customMethod }) => {
  const [text, onChangeText] = useState("")

    return (
      <View>
        <TextInput style={styles.container} value={text} onChangeText={(txt) => customMethod(txt)} placeholder="Enter"/>
      </View>
    )
}

然后在 App.js 中你有方法:

customMethod = (txt) => {
    // do something with txt variable
}

和:

<TextInputComponent customMethod={customMethod} />

可能需要进行一些调整才能使其正常工作(我没有对其进行测试),但这是一般的想法。

【讨论】:

    猜你喜欢
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2019-03-18
    • 2018-09-02
    • 1970-01-01
    • 2020-03-02
    • 2021-08-14
    相关资源
    最近更新 更多