0

我正在开发一个非常简单的提醒应用程序,作为使用 react 和 javascript 的介绍。(我是 javascript 的完整初学者,但对 ruby​​ 等语言有经验。)我希望能够从这个 TextInput 组件(https://docs.expo.io/versions/v37.0.0/ react-native/textinput/#content)不使用类。我只想将输入存储为变量,并能够在我的代码中的其他任何地方调用它。第二个函数中的 {text} 变量是我要存储第一个函数的输入的地方。(为糟糕的英语道歉)我尝试运行它,它说它找不到变量“文本”,即使那是它被分配的内容。

function NewReminderScreen({ navigation }) {
  const [value, onChangeText] = React.useState('click to add reminder.')

  return (
    <View style={styles.container}>
      <TextInput
        style={{height: 40, borderColor: 'white', borderWidth: 0, color:'#595959', fontSize:20, marginHorizontal:5}}
        onChangeText={text => onChangeText(text)}
        value = {value}
      />   
);


}

function HomeScreen({ navigation }) {

  return (
    <View style={styles.container}>
      <Text style={styles.buttontext}>{text}</Text>

      <TouchableOpacity
        onPress={() => navigation.navigate('NewReminderScreen')}
        style={styles.plusbutton}>
        <Text style={styles.buttontext}>+</Text>

      </TouchableOpacity>
    </View>
  );
}
4

2 回答 2

0

您可以尝试通过在函数外部声明一个变量并在触发 onChange 道具内部的函数时为其分配值吗?

  let text = '';

  function NewReminderScreen({ navigation }) {
  const [value, onChangeText] = React.useState('click to add reminder.')

  function textChangeHandler(event){
    onChangeText(event.target.value)
     text = event.target.value;
    }

  return (
    <View style={styles.container}>
      <TextInput
        style={{height: 40, borderColor: 'white', borderWidth: 0, color:'#595959', fontSize:20, marginHorizontal:5}}
        onChange={textChangeHandler}
        value = {value}
      />   
);


}
于 2020-04-07T05:27:10.983 回答
0

屏幕 1 你可以像这样制作一个构造函数

function NewReminderScreen({ navigation }) {
     constructor(props){
          super(props)
          this.state = {
          text: ''

          }
       }
  const [value, onChangeText] = React.useState('click to add reminder.')



 return (
    <View style={styles.container}>
      <TextInput
        style={{height: 40, borderColor: 'white', borderWidth: 0, color:'#595959', fontSize:20, marginHorizontal:5}}
        onChangeText={text => this.setState({text})}
        value = {value}
      />   
);


}

将其放入您的按钮单击功能以导航到您的主屏幕

   this.props.navigation.replace('HomeScreen', { 
     text: this.state.text
  })

屏幕 2

并在你的主屏幕渲染后把它

    const text = this.props.route.params.text;

把它放在你想要的任何地方

 <Text style={styles.buttontext}>{text}</Text>
于 2020-04-07T05:47:04.653 回答