我试图将不同TextInput的值放入一个对象中.我对一般情况下的react 还不熟悉,对状态还没有一个明确的把握.到目前为止,我的代码如下:

function App() {

  const [enteredText, setEnteredText] = useState()
  const [firstText, setFirstText] = useState()
  const [secondText, setSecondText] = useState()

  function textChange(enteredText) {
    console.log(enteredText) //I want firstText and secondText here
  }
  return (
    <View style={styles.container}>

      <Text style={styles.header}>Great one!</Text>

      <TextInput 
        value={firstText}
        onChangeText={text=>setEnteredText(text)}
        style={styles.input} 
        placeholder='1st text' />

      <TextInput 
        value={secondText}
        onChangeText={text=>setEnteredText(text)}
        style={styles.input} 
        placeholder='2nd text' />

      <Button
        onPress={()=>textChange(enteredText)}
        title='Submit'
        color='orange' />

    </View>
  );
}

export default App;

推荐答案

你真的很接近!您想要的(enteredText)实际上不应该是状态.从逻辑上讲,它是第一和第二个文本的flows,所以你可以让它是一个常数.

这样地:


function App() {

  // changed the default state to be an empty string instead of
  // the default undefined value. But either would work.
  const [firstText, setFirstText] = useState("")
  const [secondText, setSecondText] = useState("")

  const enteredText = firstText + secondText

  // I'd probably rename this function to "handleSubmit"
  function textChange() {
    console.log(enteredText)
  }

  return (
    <View style={styles.container}>

      <Text style={styles.header}>Great one!</Text>

      <TextInput 
        value={firstText}
        onChangeText={text=>setFirstText(text)}
        style={styles.input} 
        placeholder='1st text' />

      <TextInput 
        value={secondText}
        onChangeText={text=>setSecondText(text)}
        style={styles.input} 
        placeholder='2nd text' />

      <Button
        onPress={textChange}
        title='Submit'
        color='orange' />

    </View>
  );
}

export default App;

Note how I changed the 100 callbacks for the 101s

因此,您在其各自的onClick中设置了firstTextsecondText.每当状态更新时,组件都会重新加载并运行函数体中的所有代码.常量enteredText将在每次运行时创建,并且始终是两个状态的最新串联.

希望这有帮助!

Javascript相关问答推荐

简单的PayPal按钮集成导致404错误

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

可更改语言的搜索栏

如何修复我的数据表,以使stateSave正常工作?

在使用REACT更改了CSS类之后,无法更改CSS样式

让chart.js饼图中的一个切片变厚?

在VS代码上一次设置多个变量格式

AddEventListner,按键事件不工作

MongoDB中的嵌套搜索

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

P5.js中矩形内的圆弧

在Press Reaction本机和EXPO av上播放单个文件

如何处理不带参数的redux thunk payloadCreator回调函数?

如何从Reaction-Redux中来自API调用的数据中筛选值

如何将缓冲区数组转换回音频

VITE版本中的内联SVG

无法在vue3中的img src上使用v-BIND

React Native:Fetch API出现问题-无法从服务器上删除数据

如何使jQuery终端光标成为块,而不是下划线?

Reaction路由在身份验证后不会更改页面,只有在我刷新页面的情况下